Dungeon Master
Description
You are trapped in a 3D dungeon and need to find the quickest way out! The dungeon is composed of unit cubes which may or may not be filled with rock. It takes one minute to move one unit north, south, east, west, up or down. You cannot move diagonally and the maze is surrounded by solid rock on all sides.
Is an escape possible? If yes, how long will it take? Input
The input consists of a number of dungeons. Each dungeon description starts with a line containing three integers L, R and C (all limited to 30 in size).
L is the number of levels making up the dungeon. R and C are the number of rows and columns making up the plan of each level. Then there will follow L blocks of R lines each containing C characters. Each character describes one cell of the dungeon. A cell full of rock is indicated by a '#' and empty cells are represented by a '.'. Your starting position is indicated by 'S' and the exit by the letter 'E'. There's a single blank line after each level. Input is terminated by three zeroes for L, R and C. Output
Each maze generates one line of output. If it is possible to reach the exit, print a line of the form
Escaped in x minute(s). where x is replaced by the shortest time it takes to escape. If it is not possible to escape, print the line Trapped! Sample Input 3 4 5 S.... .###. .##.. ###.# ##### ##### ##.## ##... ##### ##### #.### ####E 1 3 3 S## #E# ### 0 0 0 Sample Output Escaped in 11 minute(s). Trapped! Source |
提示
你被困在一个3D地牢,需要找到最快的出路!地牢是由立方体组成。一分钟可以向北,南,东,西,上或下移动一格。你不能穿过固体岩石('#')。想逃走吗?如果是,需要多长时间?
思路:
只是数组储存变成三维,多了两个方向,还是比较好做的。
被划分到DFS分类里,但最短路最好还是用BFS,我用DFS超时了,BFS是0ms(⊙o⊙)哦。
示例程序
Source Code
Problem: 2251 Code Length: 1915B
Memory: 948K Time: 0MS
Language: GCC Result: Accepted
#include <stdio.h>
struct
{
int x,y,z,step;
}q[200000];
int tx,ty,tz,v[30][30][30],n,k,m,walk[6][3]={{0,0,1},{0,0,-1},{0,1,0},{0,-1,0},{1,0,0},{-1,0,0}}; //手动输入走法
char map[30][30][31];
int bfs(int x,int y,int z)
{
int i,f=0,top=0,x1,y1,z1;
q[top].x=x;
q[top].y=y;
q[top].z=z;
q[top].step=0;
top++;
while(f<top)
{
x=q[f].x;
y=q[f].y;
z=q[f].z;
if(x==tx&&y==ty&&z==tz)
{
return q[f].step;
}
for(i=0;6>i;i++)
{
x1=x+walk[i][0];
y1=y+walk[i][1];
z1=z+walk[i][2];
if(x1>=0&&x1<k&&y1>=0&&y1<n&&z1>=0&&z1<m&&v[x1][y1][z1]==0&&map[x1][y1][z1]!='#')
{
q[top].x=x1;
q[top].y=y1;
q[top].z=z1;
q[top].step=q[f].step+1;
top++;
v[x1][y1][z1]=1;
}
}
f++;
}
return -1;
}
int main()
{
int i,i1,i2,sx,sy,sz,t;
scanf("%d %d %d",&k,&n,&m);
while(n!=0||k!=0||m!=0)
{
for(i=0;k>i;i++)
{
for(i1=0;n>i1;i1++)
{
scanf("%s",map[i][i1]);
for(i2=0;m>i2;i2++)
{
v[i][i1][i2]=0;
if(map[i][i1][i2]=='S')
{
sx=i;
sy=i1;
sz=i2;
}
else if(map[i][i1][i2]=='E')
{
tx=i;
ty=i1;
tz=i2;
}
}
}
}
t=bfs(sx,sy,sz);
if(t!=-1)
{
printf("Escaped in %d minute(s).\n",t);
}
else
{
printf("Trapped!\n");
}
scanf("%d %d %d",&k,&n,&m);
}
return 0;
}