【HDOJ】1242 Rescue
BFS+优先级队列。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <queue> 5 using namespace std; 6 7 #define MAXNUM 205 8 9 typedef struct node_st { 10 int x, y ,t; 11 node_st() {} 12 node_st(int xx, int yy, int tt) { 13 x = xx; y = yy; t = tt; 14 } 15 friend bool operator < (node_st a, node_st b) { 16 return a.t > b.t; 17 } 18 } node_st; 19 20 int n, m; 21 char map[MAXNUM][MAXNUM]; 22 char visit[MAXNUM][MAXNUM]; 23 int direct[4][2] = {{1,0},{-1,0},{0,-1},{0,1}}; 24 25 int bfs(int x, int y) { 26 priority_queue<node_st> que; 27 node_st node; 28 int i, t; 29 30 que.push(node_st(x, y, 0)); 31 memset(visit, 0, sizeof(visit)); 32 visit[x][y] = 1; 33 34 while ( !que.empty() ) { 35 node = que.top(); 36 if (map[node.x][node.y] == 'a') 37 return node.t; 38 que.pop(); 39 t = node.t + 1; 40 for (i=0; i<4; ++i) { 41 x = node.x + direct[i][0]; 42 y = node.y + direct[i][1]; 43 if (x<0 || x>=n || y<0 || y>=m) 44 continue; 45 if (visit[x][y] || map[x][y]=='#') 46 continue; 47 if (map[x][y] == 'x') 48 que.push(node_st(x,y,t+1)); 49 else 50 que.push(node_st(x,y,t)); 51 visit[x][y] = 1; 52 } 53 } 54 55 return -1; 56 } 57 58 int main() { 59 int i, j, t; 60 int begx, begy; 61 62 while (scanf("%d %d", &n, &m) != EOF) { 63 for (i=0; i<n; ++i) { 64 scanf("%s", map[i]); 65 for (j=0; j<m; ++j) { 66 if (map[i][j] == 'r') { 67 begx = i; 68 begy = j; 69 } 70 } 71 } 72 t = bfs(begx, begy); 73 if (t == -1) 74 printf("Poor ANGEL has to stay in the prison all his life.\n"); 75 else 76 printf("%d\n", t); 77 } 78 return 0; 79 }