题目大意:给一个三维图,可以前后左右上下6种走法,走一步1分钟,求最少时间(其实就是最短路)
分析:这里与二维迷宫是一样的,只是多了2个方向可走,BFS就行(注意到DFS的话复杂度为O(6^n)肯定会TLE)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <iterator>
#include <queue>
using namespace std;
#define N 33
#define M 30000
struct p
{
int ll,rr,cc,ans;
};
typedef struct p sp;
char m[N][N][N];
int mark[N][N][N];
int l,r,c;
int dir[][]={{,-,,,,},{,,-,,,},{,,,,-,}}; void test()//可跟踪mark数组debug程序
{
int i,j,k;
for (i=;i<l;i++)
{
for (j=;j<r;j++)
{
for (k=;k<c;k++)
{
printf("%d",mark[i][j][k]);
}
printf("\n");
}
printf("\n");
}
} int lawful(int x,int y,int z)
{
if (x<||x>=l||y<||y>=r||z<||z>=c||m[x][y][z]=='#')//判断合法性要完整!!!m[x][y][z]=='#'
{
return ;
}
else
{
return ;
}
} void solve()
{
sp point,point1;
int i,j,k;
queue<p> q;//要定义在函数内,使其每次测试都能清空队列!!!
memset(mark,,sizeof(mark));
for (i=;i<l;i++)
{
for (j=;j<r;j++)
{
for (k=;k<c;k++)
{
if (m[i][j][k]=='S')
{
point.ll=i;
point.rr=j;
point.cc=k;
point.ans=;
mark[i][j][k]=;//要记得给第一步步打上标记!!!
q.push(point);
}
}
}
}
while (!q.empty())
{
point=q.front();
q.pop();
if (m[point.ll][point.rr][point.cc]=='E')
{
printf("Escaped in %d minute(s).\n",point.ans);
return;
}
for (i=;i<;i++)
{
point1.ll=point.ll+dir[][i];
point1.rr=point.rr+dir[][i];
point1.cc=point.cc+dir[][i];
point1.ans=point.ans+;
if (lawful(point1.ll,point1.rr,point1.cc)&&!mark[point1.ll][point1.rr][point1.cc])//要记得判断标记!!!
{
q.push(point1);
mark[point1.ll][point1.rr][point1.cc]=;//记得更新标记!!!
// test();
}
}
}
printf("Trapped!\n"); } int main()
{
int i,j;
while (scanf("%d %d %d",&l,&r,&c))
{
if (l==&&r==&&c==)
{
break;
}
for (i=;i<l;i++)
{
for (j=;j<r;j++)
{
scanf("%s",m[i][j]);//输入字符的快捷方法
getchar();
}
}
solve();
} return ;
}