题意:有一个三维地图长度分别为L,R,C, '.'这个为可通过区域,‘#’这个为墙, ‘S'这个为开始位置,’E'这个为出口,求从起点到出口的步数,如果不能到达输出Trapped!,否者输出步数。
求最短距离问题用bfs,bfs记得要判重。
详见代码。
简单搜索题考的是注意。
///注意细节就因为把=写成=好浪费一个小时
///当代码没有达到预期效果先看看逻辑上错没错, 然后再仔细查看代码
#include
#include
#include
#include
using namespace std;
const int N = 33;
char str[N][N][N];
int l, r, c;
int ans = 0;
struct point
{
int x;
int y;
int z;
int step;
point(){}
point(int xx, int yy, int zz, int ss)
{
x = xx;y = yy;z = zz;step = ss;
}
};
queue
que;
int dirx[6] = {1, -1, 0, 0, 0, 0};//用一些小技巧避免重复的代码,这样容易错
int diry[6] = {0, 0, 1, -1, 0, 0};
int dirz[6] = {0, 0, 0, 0, 1, -1};
int solve(point star)
{
while(!que.empty()) que.pop();
que.push(star);
while(!que.empty())
{
point tmp = que.front();
que.pop();
for(int i = 0; i < 6; i++)
{
int x = tmp.x + dirx[i];
int y = tmp.y + diry[i];
int z = tmp.z + dirz[i];
if(0 <= x && x < l && 0 <= y && y <= r && 0 <= z && z < c)
{
if(str[x][y][z] == 'E') {ans = tmp.step+1;return 1;}
if(str[x][y][z] == '.')
{
str[x][y][z] = '#';
que.push(point(x, y, z, tmp.step+1));
}
}
}
}
return 0;
}
int main(void)
{
while(scanf("%d%d%d", &l, &r, &c), l+r+c>0)
{
int i, j, k;
point star;
for(i = 0; i < l; i++)
for(j = 0; j < r; j++)
{
scanf("%s", str[i][j]);
for(k = 0; str[i][j][k]; k++)
{
if(str[i][j][k] == 'S')
{
star.x = i;
star.y = j;
star.z = k;
star.step = 0;
}
}
}
int tmp = solve(star);
if(tmp == 0)
{
printf("Trapped!\n");
}
else
{
printf("Escaped in %d minute(s).\n", ans);
}
}
return 0;
}