题目链接: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,只是有个坑点:如果当前位置为传输机(‘#’),则立刻被传送到另一层,而不能往四个方向走。(好吧,其实只是自己读题时不够认真。)
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <string>
#include <set>
#define ms(a,b) memset((a),(b),sizeof((a)))
using namespace std;
typedef long long LL;
const int INF = 2e9;
const LL LNF = 9e18;
const int MOD = 1e9+7;
const int MAXN = 10+10;
struct node //x为层, y为行, z为列。下标从1开始
{
int x, y, z, step;
};
int vis[3][MAXN][MAXN], dir[4][2] = {1,0,0,1,-1,0,0,-1};
char M[3][MAXN][MAXN];
int n, m, t;
queue<node>que;
int bfs()
{
ms(vis,0);
while(!que.empty()) que.pop();
node now, tmp;
now.x = now.y = now.z = 1;
now.step = 0;
vis[1][1][1] = 1;
que.push(now);
while(!que.empty())
{
now = que.front();
que.pop();
if(M[now.x][now.y][now.z]=='P')
return now.step;
if(M[now.x][now.y][now.z]=='#') //如果当前位置为传输机,则立刻被传送到另一层,而不能往四个方向走
{
tmp = now;
tmp.x = (now.x==1)?2:1;
if(M[tmp.x][tmp.y][tmp.z]!='*' && !vis[tmp.x][tmp.y][tmp.z])
{
vis[tmp.x][tmp.y][tmp.z] = 1;
que.push(tmp);
}
}
else for(int i = 0; i<4; i++)
{
tmp.x = now.x;
tmp.y = now.y + dir[i][0];
tmp.z = now.z + dir[i][1];
if(tmp.y>=1 && tmp.y<=n && tmp.z>=1 && tmp.z<=m &&
M[tmp.x][tmp.y][tmp.z]!='*' && !vis[tmp.x][tmp.y][tmp.z])
{
vis[tmp.x][tmp.y][tmp.z] = 1;
tmp.step = now.step + 1;
que.push(tmp);
}
}
}
return INF;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d%d",&n,&m,&t);
for(int i = 1; i<=2; i++)
for(int j = 1; j<=n; j++)
scanf("%s", M[i][j]+1);
int ans = bfs();
if(ans<=t)
puts("YES");
else
puts("NO");
}
}