您的位置:首页 > 其它

HDU2102 A计划(三维BFS)

2015-12-24 14:57 344 查看
[align=left]Problem Description[/align]
可怜的公主在一次次被魔王掳走一次次被骑士们救回来之后,而今,不幸的她再一次面临生命的考验。魔王已经发出消息说将在T时刻吃掉公主,因为他听信谣言说吃公主的肉也能长生不老。年迈的国王正是心急如焚,告招天下勇士来拯救公主。不过公主早已习以为常,她深信智勇的骑士LJ肯定能将她救出。

现据密探所报,公主被关在一个两层的迷宫里,迷宫的入口是S(0,0,0),公主的位置用P表示,时空传输机用#表示,墙用*表示,平地用.表示。骑士们一进入时空传输机就会被转到另一层的相对位置,但如果被转到的位置是墙的话,那骑士们就会被撞死。骑士们在一层中只能前后左右移动,每移动一格花1时刻。层间的移动只能通过时空传输机,且不需要任何时间。

[align=left]Input[/align]
输入的第一行C表示共有C个测试数据,每个测试数据的前一行有三个整数N,M,T。 N,M迷宫的大小N*M(1 <= N,M <=10)。T如上所意。接下去的前N*M表示迷宫的第一层的布置情况,后N*M表示迷宫第二层的布置情况。

[align=left]Output[/align]
如果骑士们能够在T时刻能找到公主就输出“YES”,否则输出“NO”。

[align=left]Sample Input[/align]

1
5 5 14
S*#*.
.#...
.....
****.
...#.

..*.P
#.*..
***..
...*.
*.#..


[align=left]Sample Output[/align]

YES


原本以为昨天已经搞了一晚上的BFS,今天这道题肯定没问题了,没想到还是WA了,折腾了两节中近纲,心累。主要在判断是否超过时间和是否达到公主的位置的地方出了错,原本我是这样写的。

if(map[now.floor][now.x][now.y]=='P')
{
cout<<"YES"<<endl;
return;
}
if(now.step>=t)
{
cout<<"NO"<<endl;
return;
}
然后改成了这样

把>=t改成了>t,还是错了

后来改成了这样

if(map[now.floor][now.x][now.y]=='P')
{
if(now.step<=t)
{
cout<<"YES"<<endl;
return;
}
else
break;
}
发现AC了之后,我思考,为什么上面的代码会错误。发现要先判断时间!

于是我改成了下面的样子,也AC了。

if(now.step>t)
{
cout<<"NO"<<endl;
return;
}
if(map[now.floor][now.x][now.y]=='P')
{
cout<<"YES"<<endl;
return;
}


完整的代码如下:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
struct node
{
int x,y;
int floor;
int step;
};
char map[2][15][15];
int vis[2][15][15];
int n,m,t;
node s;
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
int check(int i,int j)
{
if(map[0][i][j]==0)
return 0;
return 1;
}
int can(int floor,int i,int j)
{
if(vis[floor][i][j]==1)
return 0;
if(map[floor][i][j]=='*')
return 0;
return 1;
}
void bfs()
{
queue<node> q;
s.x=1;
s.y=1;
s.floor=0;
s.step=0;
q.push(s);
vis[s.floor][s.x][s.y]=1;
while(!q.empty())
{
node now=q.front();
q.pop();
if(now.step>t) { cout<<"NO"<<endl; return; } if(map[now.floor][now.x][now.y]=='P') { cout<<"YES"<<endl; return; }
for(int i=0;i<4;i++)
{
node next;
next.x=now.x+dir[i][0];
next.y=now.y+dir[i][1];
next.step=now.step+1;
next.floor=now.floor;
if(!check(next.x,next.y))
continue;
if(!can(next.floor,next.x,next.y))
continue;
if(map[next.floor][next.x][next.y]=='#')
{
next.floor=next.floor^1;
if(!can(next.floor,next.x,next.y)||map[next.floor][next.x][next.y]=='#')
continue;
}
vis[next.floor][next.x][next.y]=1;
q.push(next);
}

}
cout<<"NO"<<endl;
}
int main(void)
{
int c,i,j;
cin>>c;
while(c--)
{
memset(map,0,sizeof(map));
memset(vis,0,sizeof(vis));
cin>>n>>m>>t;
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
cin>>map[0][i][j];
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
cin>>map[1][i][j];
bfs();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: