HDU 2102 BFS

题目

题意:骑士要找公主,迷宫有两层,层与层之间用传送门连接;

题解:BFS,注意如果有传送门的话,检查另一端,如果是墙或者是传送门就不走,就阔以了。注意传送门传送不记步,但是走到传送门记步。

#include <iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
struct node{
	int f,x,y;
	int step;
}a;
int n,m,t,pf,px,py;
char mp[2][12][12];
int vis[2][12][12];
int dir[4][2]={1,0,-1,0,0,1,0,-1};
int check(int f,int x,int y){
	if(vis[f][x][y])return 1;
	if(x<1||x>n||y<1||y>m)return 1;
	if(mp[f][x][y]=='*')return 1;
	return 0;
}
int bfs(){
	a.x=a.y=1;
	a.step=a.f=0;
	queue<node >que;
	int i,xx,yy,ff;
	que.push(a);
	node next;
	while(!que.empty()){
		a=que.front();
		que.pop();
		vis[a.f][a.x][a.y]=1;
		if(a.step>t)break;
		if(mp[a.f][a.x][a.y]=='P')return a.step;
		for(i=0;i<4;i++){
			xx=a.x+dir[i][0];
			yy=a.y+dir[i][1];
			if(check(a.f,xx,yy))continue ;
			if(mp[a.f][xx][yy]=='#'){
				if(mp[!a.f][xx][yy]=='#')continue ;
				else if(mp[!a.f][xx][yy]=='*')continue;
				next.x=xx;
				next.y=yy;
				next.f=!a.f;
				next.step=a.step+1;
				que.push(next);
				continue;
			}
			next.x=xx;
			next.y=yy;
			next.f=a.f;
			next.step=a.step+1;
			que.push(next);
		}
	}
	return -1;
}
int main()
{
	int c,i,j;
	scanf("%d",&c);
	while(c--){
		scanf("%d%d%d",&n,&m,&t);
		memset(vis,0,sizeof(vis));
		for(i=1;i<=n;i++)for(j=1;j<=m;j++)cin>>mp[0][i][j];
		for(i=1;i<=n;i++)for(j=1;j<=m;j++)cin>>mp[1][i][j];
		int ans=bfs();
		if(ans==-1)printf("NO\n");
		else printf("YES\n");
	}
    return 0;
}

猜你喜欢

转载自blog.csdn.net/nwpu2017300135/article/details/80413768