hdoj1072 Nightmare bfs
题意:在一个地图里逃亡,2是起点,3是终点,1是路,0是墙,逃亡者携带一个炸弹,6分钟就会炸,要在6分钟前到达4可以重制时间,问是否能逃亡,若能则输出最小值
我的思路:bfs在5步内是否存在3,存在则输出退出。记录到达每一点剩余时间,如果再次到达某点的剩余时间大于原剩余时间则更新,加入队列。
1 #include <iostream> 2 #include <cstring> 3 #include <queue> 4 5 using namespace std; 6 const int M = 10; 7 int map[M][M]; 8 int graph[M][M]; 9 struct node 10 { 11 int x,y; 12 int step; 13 int time; 14 }; 15 16 node now,nn,next1; 17 queue <struct node> q; 18 int n,m; 19 int dire[4][2] = {{-1,0},{0,-1},{1,0},{0,1}}; 20 21 int bfs() 22 { 23 while (!q.empty()) 24 { 25 now = q.front(); 26 q.pop(); 27 for (int i = 0;i < 4;i++) 28 { 29 int x = now.x + dire[i][0]; 30 int y = now.y + dire[i][1]; 31 if (x>=0 && x<n && y>=0 && y<m && map[x][y] != 0 && map[x][y]!=2 && now.time-1>0) //踩点到到达4也会爆炸 32 { 33 next1.x = x; 34 next1.y = y; 35 if (map[x][y] == 3) 36 { 37 return now.step+1; 38 } 39 if (map[x][y] == 4) 40 { 41 next1.time = 6; 42 } 43 else next1.time = now.time - 1; 44 next1.step = now.step+1; 45 if (next1.time > graph[x][y]) //加入队列条件 46 { 47 graph[x][y] = next1.time; 48 q.push(next1); 49 } 50 } 51 } 52 } 53 return -1; 54 } 55 int main() 56 { 57 int t; 58 cin >> t; 59 while (t--) 60 { 61 cin >> n >> m; 62 while (!q.empty()) 63 q.pop(); 64 for (int i = 0;i < n;i++) 65 { 66 for (int j = 0;j < m;j++) 67 { 68 cin >> map[i][j]; 69 graph[i][j] = 0; 70 if (map[i][j] == 2) 71 { 72 nn.x = i; 73 nn.y = j; 74 nn.step = 0; 75 nn.time = 6; 76 q.push(nn); 77 } 78 } 79 } 80 cout << bfs() << endl; 81 } 82 return 0; 83 }