仙岛求药
//仙岛求药
#include <iostream> #include <cstdio> #include <cstring> #include <queue>
using namespace std;
typedef struct _node { int x,y,z; }node;
const int N=100; const int b[4][2]={{1,0},{0,1},{-1,0},{0,-1}}; //对四个方向打表 bool map[N][N]; //纪录走过的点 char graph[N][N]; int n,m; node sstart,send;
void inIt() { memset(map,false,sizeof(map)); //每次要清理标记 char ctemp; for(int i=0;i<n;i++) { scanf("%s",graph[i]); for(int j=0;j<m;j++) { if(graph[i][j]=='.') map[i][j]=true; else if(graph[i][j]=='@') { sstart.x=i; sstart.y=j; sstart.z=0; } else if(graph[i][j]=='*') { send.x=i; send.y=j; map[i][j]=true; } } } }
void bfs() { queue<node> q; q.push(sstart); while(!q.empty()) { node a=q.front(); q.pop(); if(a.x==send.x&&a.y==send.y) { printf("%d\n",a.z); return ; } for(int i=0;i<4;i++) { int x=a.x+b[i][0]; int y=a.y+b[i][1]; if(map[x][y]&&x>=0&&x<n&&y>=0&&y<m) //如果点可走 入队 { node c; c.x=x; c.y=y; c.z=a.z+1; q.push(c); map[x][y]=false; //标记点可走 } } } printf("-1\n"); }
int main() { while(scanf("%d%d",&n,&m),n+m) { inIt(); bfs(); } return 0; }