POJ-2251Dungeon Maste(BFS三维模板题)

题目链接:
https://cn.vjudge.net/problem/POJ-2251

题解:
@时夜 大佬的帮助下完成。

代码:

//BFS(队列)
#include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>
using namespace std;
int vis[33][33][33];
char mapp[33][33][33];
int L,R,C;
int dir[6][3]=
{1,0,0,-1,0,0,0,0,-1,0,0,1,0,-1,0,0,1,0};//方向数组
struct node
{
	int x,y,z;
	int step;
};
node s,e;//起点和终点节点
void Getdata()
{
	char c;
	for(int i=1;i<=L;i++)
	{
		for(int j=1;j<=R;j++)
		{
			for(int k=1;k<=C;k++)
			{
				scanf(" %c",&c);
				mapp[i][j][k]=c;
				//记录起点和终点
				if(c=='S') s.x=i,s.y=j,s.z=k;
				else if(c=='E') e.x=i,e.y=j,e.z=k;
			}
		}
	}
}
int bfs(node s)
{
	s.step=0;
	queue<node> q;
	q.push(s);
	node top,now;
	while(!q.empty())
	{
		top=q.front();
		q.pop();
		for(int i=0;i<6;i++)
		{//六个方向去寻找
			now.x=top.x+dir[i][0];
			now.y=top.y+dir[i][1];
			now.z=top.z+dir[i][2];
			if(now.x>=1&&now.x<=L&&now.y>=1&&now.y<=R&&now.z>=1&&now.z<=C&&!vis[now.x][now.y][now.z]&&mapp[now.x][now.y][now.z]!='#')
			{//判断是否越界,是否能走,是否已走
				now.step=top.step+1;
				vis[now.x][now.y][now.z]=1;//标记已走
				q.push(now);
				if(now.x==e.x&&now.y==e.y&&now.z==e.z)//判断是否到达终点
					return now.step;
			}
		}
	}
	return 0;
}
int main()
{
	int ans;
	while(scanf("%d%d%d",&L,&R,&C)&&L!=0)
	{
		memset(vis,0,sizeof(vis));
		Getdata();
		ans=bfs(s);
		if(ans==0)
			printf("Trapped!\n");
		else
			printf("Escaped in %d minute(s).\n",ans);
	}
	return 0;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值