杭电1242
Sample Input
7 8
#.#####.
#.a#..r.
#..#x...
..#..#.#
#...##..
.#......
........
Sample Output
13
View Code
1 //杭电1242 2 #include<stdio.h> 3 #include<queue> 4 using namespace std; 5 #define N 202 6 char map[N][N]; 7 int mark[N][N]; 8 int m,n,x,y,flag; 9 int d[4][2]={1,0,-1,0,0,1,0,-1}; 10 typedef struct 11 { 12 int x; 13 int y; 14 int step; 15 }point; 16 void dfs() 17 { 18 queue<point>q; 19 point p,c,t; 20 int i; 21 p.x=x; 22 p.y=y; 23 p.step=0; 24 mark[x][y]=1;//标记起始点以走过,防止重复 25 26 flag=0; 27 q.push(p); 28 while(!q.empty()) 29 { 30 c=q.front();//取队头元素 31 32 q.pop();//队头元素出队 33 34 if(map[c.x][c.y]=='x')//如果遇到卫兵,则时间加1,入队该点,并将该点变成可行路径 35 { 36 c.step++; 37 map[c.x][c.y]='.'; 38 q.push(c); 39 } 40 else 41 { 42 for(i=0;i<4;i++) //扫描四周,寻找路径 43 44 { 45 t.x=c.x+d[i][0]; 46 t.y=c.y+d[i][1]; 47 t.step=c.step+1; 48 if(map[t.x][t.y]!='#'&&mark[t.x][t.y]==0&&t.x>=0&&t.y>=0&&t.x<m&&t.y<n) 49 { 50 if(map[t.x][t.y]=='a') //如果找到则输出 51 { 52 printf("%d\n",t.step); 53 flag=1; 54 return; 55 } 56 //没找到则入队该点继续寻找 57 58 mark[t.x][t.y]=1; 59 q.push(t); 60 } 61 } 62 } 63 } 64 if(flag==0) 65 printf("Poor ANGEL has to stay in the prison all his life.\n"); 66 } 67 68 69 int main() 70 { 71 int i,j; 72 while(scanf("%d%d",&m,&n)!=-1) 73 { 74 for(i=0;i<m;i++) 75 scanf("%s",map[i]); 76 for(i=0;i<m;i++) 77 { 78 for(j=0;j<n;j++) 79 { 80 if(map[i][j]=='r')//标记初始点 81 { 82 x=i; 83 y=j; 84 } 85 mark[i][j]=0;//初始化标记数组 86 } 87 } 88 dfs(); 89 } 90 return 0; 91 }