【HDOJ】1072 Nightmare
bfs,使用ttl进行剪枝。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <queue> 5 using namespace std; 6 7 #define MAXNUM 10 8 9 int map[MAXNUM][MAXNUM], ttls[MAXNUM][MAXNUM], n, m; 10 int direct[4][2] = {{-1,0},{1,0},{0,-1},{0,1}}; 11 12 typedef struct node_st { 13 int ttl; 14 int t; 15 int x, y; 16 node_st() {} 17 node_st(int ttll, int tt, int xx, int yy) { 18 ttl = ttll; 19 t = tt; 20 x = xx; 21 y = yy; 22 } 23 } node_st; 24 25 int bfs(int begx, int begy) { 26 int val = -1; 27 int x=begx, y=begy, ttl=6, t=0; 28 int newx, newy, newt, newttl; 29 queue<node_st> nodes; 30 node_st node; 31 32 memset(ttls, 0, sizeof(ttls)); 33 nodes.push(node_st(ttl,t,x,y)); 34 map[x][y] = 0; 35 36 while ( !nodes.empty() ) { 37 node = nodes.front(); 38 nodes.pop(); 39 x = node.x; 40 y = node.y; 41 ttl = node.ttl; 42 t = node.t; 43 if (map[x][y]==3 && ttl) { 44 val = node.t; 45 break; 46 } 47 --ttl; ++t; 48 if (ttl == 0) 49 continue; 50 for (int i=0; i<4; ++i) { 51 newx = x + direct[i][0]; 52 newy = y + direct[i][1]; 53 newttl = ttl; 54 newt = t; 55 if (newx<0 || newx>=n || newy<0 || newy>=m) 56 continue; 57 if (map[newx][newy] == 0) 58 continue; 59 if (map[newx][newy] == 4) { 60 newttl = 6; 61 map[newx][newy] = 0; 62 } 63 if (newttl > ttls[newx][newy]) { 64 ttls[newx][newy] = newttl; 65 nodes.push(node_st(newttl, newt, newx, newy)); 66 } 67 } 68 } 69 70 return val; 71 } 72 73 int main() { 74 int t; 75 int i, j, begx, begy; 76 77 scanf("%d", &t); 78 79 while (t--) { 80 scanf("%d %d", &n, &m); 81 for (i=0; i<n; ++i) { 82 for (j=0; j<m; ++j) { 83 scanf("%d", &map[i][j]); 84 if (map[i][j] == 2) { 85 begx = i; 86 begy = j; 87 } 88 } 89 } 90 i = bfs(begx, begy); 91 printf("%d\n", i); 92 } 93 94 return 0; 95 }