优先队列,这道题被坑了,心情不好。
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 #include <queue> 5 #define MAX 200 6 using namespace std; 7 typedef struct node 8 { 9 int x,y; 10 int move; 11 12 }point; 13 point start; 14 //把move设置为优先级变量,top()返回最小的队 15 bool operator <(node n1,node n2) 16 { 17 return n1.move>n2.move; 18 } 19 20 int N,M; 21 const int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}}; 22 char map[MAX][MAX]; 23 24 void Bfs(void); 25 int main() 26 { 27 while(~scanf("%d %d",&N,&M))//~是把-1变成0 28 { 29 memset(map,0,sizeof(map)); 30 for(int i=0;i<N;i++) 31 for(int j=0;j<M;j++) 32 { 33 //cin>>map[i][j]; 34 scanf("%1s",&map[i][j]); 35 if(map[i][j]=='a') 36 start.x=i,start.y=j; 37 } 38 start.move=0; 39 Bfs(); 40 } 41 return 0; 42 } 43 44 void Bfs() 45 { 46 int visit[MAX][MAX]; 47 memset(visit,0,sizeof(visit)); 48 visit[start.x][start.y]=1; 49 50 priority_queue<point>p; 51 p.push(start); 52 point temp,next; 53 54 while(!p.empty()) 55 { 56 temp=p.top(); 57 p.pop(); 58 for(int i=0;i<4;i++) 59 { 60 next.x=temp.x+dir[i][0]; 61 next.y=temp.y+dir[i][1]; 62 if(!visit[next.x][next.y] && map[next.x][next.y]!='#' && next.x>=0&&next.x<N && next.y>=0&&next.y<M) 63 { 64 visit[next.x][next.y]=1; 65 if(map[next.x][next.y]=='x') 66 next.move=temp.move+2; 67 else if(map[next.x][next.y]=='.') 68 next.move=temp.move+1; 69 else if(map[next.x][next.y]=='r') 70 { 71 next.move=temp.move+1; 72 printf("%d\n",next.move); 73 return; 74 } 75 p.push(next); 76 } 77 } 78 } 79 printf("Poor ANGEL has to stay in the prison all his life.\n"); 80 return; 81 } 82 /* 83 7 8 84 #.#####. 85 #.a#..r. 86 #..#x... 87 ..#..#.# 88 #...##.. 89 .#...... 90 ........ 91 */