题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2102
A计划
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 24298 Accepted Submission(s): 6095
Problem Description
可怜的公主在一次次被魔王掳走一次次被骑士们救回来之后,而今,不幸的她再一次面临生命的考验。魔王已经发出消息说将在T时刻吃掉公主,因为他听信谣言说吃公主的肉也能长生不老。年迈的国王正是心急如焚,告招天下勇士来拯救公主。不过公主早已习以为常,她深信智勇的骑士LJ肯定能将她救出。
现据密探所报,公主被关在一个两层的迷宫里,迷宫的入口是S(0,0,0),公主的位置用P表示,时空传输机用#表示,墙用*表示,平地用.表示。骑士们一进入时空传输机就会被转到另一层的相对位置,但如果被转到的位置是墙的话,那骑士们就会被撞死。骑士们在一层中只能前后左右移动,每移动一格花1时刻。层间的移动只能通过时空传输机,且不需要任何时间。
现据密探所报,公主被关在一个两层的迷宫里,迷宫的入口是S(0,0,0),公主的位置用P表示,时空传输机用#表示,墙用*表示,平地用.表示。骑士们一进入时空传输机就会被转到另一层的相对位置,但如果被转到的位置是墙的话,那骑士们就会被撞死。骑士们在一层中只能前后左右移动,每移动一格花1时刻。层间的移动只能通过时空传输机,且不需要任何时间。
Input
输入的第一行C表示共有C个测试数据,每个测试数据的前一行有三个整数N,M,T。 N,M迷宫的大小N*M(1 <= N,M <=10)。T如上所意。接下去的前N*M表示迷宫的第一层的布置情况,后N*M表示迷宫第二层的布置情况。
Output
如果骑士们能够在T时刻能找到公主就输出“YES”,否则输出“NO”。
Sample Input
1
5 5 14
S*#*.
.#...
.....
****.
...#.
..*.P
#.*..
***..
...*.
*.#..
Sample Output
YES
Source
题解:
比较简单的BFS,只是有个坑点:如果当前位置为传输机(‘#’),则立刻被传送到另一层,而不能往四个方向走。(好吧,其实只是自己读题时不够认真。)
代码如下:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 #include <algorithm> 6 #include <vector> 7 #include <queue> 8 #include <stack> 9 #include <map> 10 #include <string> 11 #include <set> 12 #define ms(a,b) memset((a),(b),sizeof((a))) 13 using namespace std; 14 typedef long long LL; 15 const int INF = 2e9; 16 const LL LNF = 9e18; 17 const int MOD = 1e9+7; 18 const int MAXN = 10+10; 19 20 struct node //x为层, y为行, z为列。下标从1开始 21 { 22 int x, y, z, step; 23 }; 24 int vis[3][MAXN][MAXN], dir[4][2] = {1,0,0,1,-1,0,0,-1}; 25 char M[3][MAXN][MAXN]; 26 int n, m, t; 27 28 queue<node>que; 29 int bfs() 30 { 31 ms(vis,0); 32 while(!que.empty()) que.pop(); 33 34 node now, tmp; 35 now.x = now.y = now.z = 1; 36 now.step = 0; 37 vis[1][1][1] = 1; 38 que.push(now); 39 40 while(!que.empty()) 41 { 42 now = que.front(); 43 que.pop(); 44 45 if(M[now.x][now.y][now.z]=='P') 46 return now.step; 47 48 if(M[now.x][now.y][now.z]=='#') //如果当前位置为传输机,则立刻被传送到另一层,而不能往四个方向走 49 { 50 tmp = now; 51 tmp.x = (now.x==1)?2:1; 52 if(M[tmp.x][tmp.y][tmp.z]!='*' && !vis[tmp.x][tmp.y][tmp.z]) 53 { 54 vis[tmp.x][tmp.y][tmp.z] = 1; 55 que.push(tmp); 56 } 57 } 58 59 else for(int i = 0; i<4; i++) 60 { 61 tmp.x = now.x; 62 tmp.y = now.y + dir[i][0]; 63 tmp.z = now.z + dir[i][1]; 64 if(tmp.y>=1 && tmp.y<=n && tmp.z>=1 && tmp.z<=m && 65 M[tmp.x][tmp.y][tmp.z]!='*' && !vis[tmp.x][tmp.y][tmp.z]) 66 { 67 vis[tmp.x][tmp.y][tmp.z] = 1; 68 tmp.step = now.step + 1; 69 que.push(tmp); 70 } 71 } 72 } 73 return INF; 74 } 75 76 int main() 77 { 78 int T; 79 scanf("%d",&T); 80 while(T--) 81 { 82 scanf("%d%d%d",&n,&m,&t); 83 for(int i = 1; i<=2; i++) 84 for(int j = 1; j<=n; j++) 85 scanf("%s", M[i][j]+1); 86 87 int ans = bfs(); 88 if(ans<=t) 89 puts("YES"); 90 else 91 puts("NO"); 92 } 93 }