Week 12 B——三维空间

必做题 - 2

zjm被困在一个三维的空间中,现在要寻找最短路径逃生!
空间由立方体单位构成。
zjm每次向上下前后左右移动一个单位需要一分钟,且zjm不能对角线移动。
空间的四周封闭。zjm的目标是走到空间的出口。
是否存在逃出生天的可能性?如果存在,则需要多少时间?

Input

输入第一行是一个数表示空间的数量。 每个空间的描述的第一行为L,R和C(皆不超过30)。
L表示空间的高度,R和C分别表示每层空间的行与列的大小。 随后L层,每层R行,每行C个字符。
每个字符表示空间的一个单元。’#‘表示不可通过单元,’.‘表示空白单元。 zjm的起始位置在’S’,出口为’E’。每层空间后都有一个空行。
L,R和C均为0时输入结束。

Output

每个空间对应一行输出。 如果可以逃生,则输出如下 Escaped in x minute(s). x为最短脱离时间。

如果无法逃生,则输出如下 Trapped!

Sample Input

3 4 5
S….
.###.
.##..
###.#

#####
#####
##.##
##…

#####
#####
#.###
####E

1 3 3
S##
#E#
###

0 0 0

Sample Outpu

Escaped in 11 minute(s).
Trapped!

问题分析

可以看出这是个BFS遍历问题,唯一不一样的就是用的是三维数组。但是影响不大,只是方向变成了三维的。
用一个数组存放方向:

int dir[6][3]={1,0,0,0,1,0,0,0,1,0,0,-1,-1,0,0,0,-1,0};

在BFS的时候,每次从队列中弹出一个坐标,六个方向全都遍历一遍,计算出下一个位置的坐标,将符合要求的坐标入队。循环知道队列为空,或者走到了终点。

代码实现

#include<iostream>
#include<string>
#include<queue> 
using namespace std;

struct pos
{
	int x,y,z;
	int time;
};

int dir[6][3]={1,0,0,0,1,0,0,0,1,0,0,-1,-1,0,0,0,-1,0};


int l,r,c;
int a[32][32][32];
bool vis[32][32][32];
string start;
pos st;
int suc;

void bfs(pos st)
{
	queue<pos> q;
	pos now,next;
	st.time=0;
	q.push(st);
	vis[st.x][st.y][st.z]=true;
	
	while(!q.empty())
	{
		now = q.front();
//		cout<<now.x<<" "<<now.y<<" "<<now.z<<endl;
		q.pop();
		if(a[now.x][now.y][now.z] == 3)
		{
			suc = now.time;
			return;
		}
		for(int i=0; i<6; i++)
		{
			next.x=now.x+dir[i][0];
			next.y=now.y+dir[i][1];
			next.z=now.z+dir[i][2];
			next.time = now.time+1;
			//cout<<next.x<<" "<<next.y<<" "<<next.z<<endl;
			
			if(!vis[next.x][next.y][next.z] && next.x<l && next.x >=0 
			&& next.y<r && next.y>=0 && next.z<c && next.z>=0 
			&& a[next.x][next.y][next.z] != 1) 
			{
				q.push(next);
			 }
			vis[next.x][next.y][next.z] = true;
		}
	}
}

int main()
{
	cin>>l>>r>>c;
	pos st;
	while(!(l==0&&r==0&&c==0))
	{
		suc=-1;
		for(int i=0; i<l; i++)
		{
			for(int j=0; j<r; j++)
			{
				cin>>start;
		    	for(int k=0; k<start.size(); k++)
			    {
			        vis[i][j][k]=0;
				    if(start[k]=='#') a[i][j][k]=1;
				    else if(start[k]=='.') a[i][j][k]=0;
				    else if(start[k]=='S')
				    {
				   	    a[i][j][k]=2;
				   	    vis[i][j][k]=1;
				   	    st.x=i;
				   	    st.y=j;
				   	    st.z=k;
					 } 
				    else
					{
						a[i][j][k]=3;
					 } 
		    	}
			}
			
			
		}
		
		bfs(st);
		
		if(suc!=-1) cout<<"Escaped in "<<suc<<" minute(s)."<<endl;
		else cout<<"Trapped!"<<endl;	
				
		cin>>l>>r>>c;
		
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值