问题链接:Problem F
问题简述:
公主被魔王关押在了一个二层迷宫中,T时刻后将被不可描述,迷宫中有时空传送器,一旦勇士踏入传送器中,就会被强制传送到下一层的相同位置(传送过程不耗费时间),若下一层的相同位置是墙,则勇士直接撞死,问勇士能否在T时刻之前救出公主?
问题分析:
注意问题是在T时刻之前救出公主便算成功,而非一定要在T时刻救出公主,因此问题可以转换为求最短路径,再将最短路径耗费的时间与T作比较即可得出答案。本题难点在于对时空传送器的处理,在这里需要注意两个坑点:
1.当时空传送器的目的地同样是传送器时,勇士将会无限向两层传送,视作死亡;
2.时空传送器有可能直接传送到公主坐在位置。
程序说明:
对二层的立体迷宫使用了一个三维数组储存,遇上时空传送器时,直接将第三维度加一减一即可,方便操作。
AC通过的C++语言程序如下:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<queue>
#include<set>
#include<cstring>
#include<cmath>
using namespace std;
char map[2][15][15];
int n,m,t;
int dir[4][2]={1,0,-1,0,0,1,0,-1};
bool vis[2][15][15];
struct node{
int x;
int y;
int z;
int step;
};
bool edge(int x,int y,int z){
if(x>=0&&y>=0&&x<n&&y<m&&map[z][x][y]!='*'&&vis[z][x][y]==0){
return 1;
}
else{
return 0;
}
}
bool BFS(){
queue<node>q;
node p1;
p1.x=0;
p1.y=0;
p1.z=0;
p1.step=0;
vis[0][0][0]=1;
q.push(p1);
while(!q.empty()){
node p2=q.front();
q.pop();
if(map[p2.z][p2.x][p2.y]=='P'&&p2.step<=t){
return 1;
}
if(p2.step>t){
return 0;
}
if(map[p2.z][p2.x][p2.y]=='#'){
if(p2.z==0){
if(map[p2.z+1][p2.x][p2.y]!='#'&&map[p2.z+1][p2.x][p2.y]!='*'){
p2.z=p2.z+1;
vis[p2.z][p2.x][p2.y]=1;
if(map[p2.z][p2.x][p2.y]=='P'&&p2.step<=t){
return 1;
}
if(p2.step>t){
return 0;
}
}
else{
continue;
}
}
else if(p2.z==1){
if(map[p2.z-1][p2.x][p2.y]!='#'&&map[p2.z-1][p2.x][p2.y]!='*'){
p2.z=p2.z-1;
vis[p2.z][p2.x][p2.y]=1;
if(map[p2.z][p2.x][p2.y]=='P'&&p2.step<=t){
return 1;
}
if(p2.step>t){
return 0;
}
}
else{
continue;
}
}
}
for(int i=0;i<4;i++){
int next_x=p2.x+dir[i][0];
int next_y=p2.y+dir[i][1];
if(edge(next_x,next_y,p2.z)){
p1.x=next_x;
p1.y=next_y;
p1.z=p2.z;
p1.step=p2.step+1;
vis[p1.z][p1.x][p1.y]=1;
q.push(p1);
}
}
}
return 0;
}
int main(){
std::ios::sync_with_stdio(false);
int c;
cin>>c;
while(c--){
memset(vis,0,sizeof(vis));
cin>>n>>m>>t;
for(int z=0;z<=1;z++){
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>map[z][i][j];
}
}
}
bool ans=BFS();
if(ans){
cout<<"YES"<<endl;
}
else{
cout<<"NO"<<endl;
}
}
}