HDOJ2102(A计划) bfs
A计划
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1412 Accepted Submission(s): 291
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
//1245841 2009-04-08 07:58:12 Accepted 2102 15MS 232K 2206 B C++ Xredman
#include <iostream>
#include <queue>
using namespace std;
const int N = 12;
typedef struct
{
int x,y;
int l, cost;
}Node;
char Maze[2][N][N];
bool Visited[2][N][N];
int n, m, t;
int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
void init()
{
int i, j;
for(i = 0; i < n; i++)
cin>>Maze[0][i];
for(i = 0; i < n; i++)
cin>>Maze[1][i];
for(i = 0; i < n; i++)
for(j = 0; j < m; j++)
{
Visited[0][i][j] =
Visited[1][i][j] = false;
}
}
bool isBound(int x, int y)
{
if(x < 0 || y < 0)
return false;
if(x >= n || y >= m)
return false;
return true;
}
bool bfs()
{
queue<Node> Q;
Node a, b;
int i;
a.x = a.y = a.l = a.cost = 0;
Visited[a.l][a.x][a.y] = true;
Q.push(a);
while(! Q.empty())
{
a = Q.front();
Q.pop();
if(Maze[a.l][a.x][a.y] == '#')
{
b.x = a.x; b.y= a.y; b.cost = a.cost;
if(a.l == 0)
b.l = 1;
else
b.l = 0;
if(Maze[b.l][b.x][b.y] != '*' && !Visited[b.l][b.x][b.y])
{
if(Maze[b.l][b.x][b.y] == 'P')
{
if(b.cost <= t)
return true;
else
return false;
}
Visited[b.l][b.x][b.y] = true;
Q.push(b);
}
continue;
}
for(i = 0; i < 4; i++)
{
b.x = a.x + dir[i][0];
b.y = a.y + dir[i][1];
b.l = a.l;
b.cost = a.cost + 1;
if( isBound(b.x, b.y) &&
Maze[b.l][b.x][b.y] != '*' &&
!Visited[b.l][b.x][b.y])
{
if(Maze[b.l][b.x][b.y] == 'P')
{
if(b.cost <= t)
return true;
else
return false;
}
Visited[b.l][b.x][b.y] = true;
Q.push(b);
}
}
}
return false;
}
int main()
{
int C;
while(cin>>C)
while(C--)
{
cin>>n>>m>>t;
init();
if(bfs())
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
return 0;
}