思路:
bfs;
来,上代码:
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; #define maxm 10005 const int dx[5]={0,-1,0,1,0}; const int dy[5]={0,0,1,0,-1}; int n,m,quex[maxm],quey[maxm],qued[maxm]; char map[25][25]; bool if_[25][25]; int bfs() { int sx,sy,h=0,tail=1; for(int i=1;i<=n;i++) { scanf("%s",map[i]+1); for(int j=1;j<=m;j++) { if_[i][j]=true; if(map[i][j]=='@') sx=i,sy=j; } } quex[0]=sx,quey[0]=sy,qued[0]=0,if_[sx][sy]=false; while(h<tail) { int nowx=quex[h],nowy=quey[h],d=qued[h++]; for(int i=1;i<=4;i++) { int x=nowx+dx[i],y=nowy+dy[i],dd=d+1; if(x>0&&x<=n&&y>0&&y<=m&&(map[x][y]=='.'||map[x][y]=='*')&&if_[x][y]) { if(map[x][y]=='*') return dd; if_[x][y]=false; quex[tail]=x,quey[tail]=y,qued[tail++]=dd; } } } return -1; } int main() { scanf("%d%d",&n,&m); while(n!=0&&m!=0) cout<<bfs()<<endl,scanf("%d%d",&n,&m);; return 0; }