题意:给一个有L层的地牢,每层有R行C列,‘S’代表入口,‘E’代表出口。‘#’不可行走,‘.’可以行走,问从S到E的最短距离是?
真的是太久不写搜索了……最短路径问题一般使用bfs更多,而如果需要生成全部能遍历到的状态,则通常使用dfs。所以这道题当然就要使用bfs啦!
学到了几个小技巧:
- 以0 0 0结束多组输入的问题,可以不写三个X != 0,而直接用X+Y+Z != 0来简化代码。
- 二维搜索表示下一步行走方向时使用[2][4],三维这里懵逼了,后来看了题解才晓得是[3][6]这里其实不难理解,我们统一使用二维数组来存储direction,direction[a][b],a表示维数,b表示方向数。
- 很迷的POJ…必须用G++编译(。
还有hin重要的一点: scanf读char数组对getchar()的使用……二维的时候是在外层循环加getchar,三维这个就有点麻烦,搞了半天没搞定,看了一下题解,主要是有两种写法(不管哪一个前面那个getchar()都可以省略):
- 一种是使用cin逐个字符的读;
getchar();
char c;
for(int i = 1;i <= L;i++)
{
for(int j = 1;j <= R;j++)
{
for(int m = 1;m <= C;m++)
{
cin >> c;
matrix[i][j][m] = c;
if(c == 'S')
startz = i, startx = j, starty = m;
}
}
}
- 一种是借助char数组,相当于直接用地址往里放(?)
getchar();
for(int i = 1;i <= L;i++)
{
for(int j = 1;j <= R;j++)
{
scanf("%s", matrix[i][j]+1);
for(int m = 1;m <= C;m++)
{
if(matrix[i][j][m] == 'S')
startz = i, startx = j, starty = m;
}
}
}
我也不清楚原理但是就先记住好了
关于BFS一开始理解不到位的一点
最开始WA是逐个试探入队的时候没有加标记(mark[][][]=1),所以MLE了。可以这么想,bfs是逐层向外,不断入队,所以当前点扫了一圈之后这一圈都要加标记,不然扫到这一圈的某个点的时候必然会把当前点再次入队,那么就无限重复下去了。
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
#define ll long long
//(all limited to 30 in size).
int L, //高
R, //行
C, //列
ans;//存储答案
int startx, starty, startz;
char matrix [31][31][31];
int mark[31][31][31],//记录这一点有没有走过
direction[6][3] = {0, 0, 1, 0, 0, -1,
1, 0, 0, -1, 0, 0,
0, 1, 0, 0, -1, 0};
struct node
{
int x, y, z, step;
};
int main()
{
//S E
while(scanf("%d %d %d", &L, &R, &C) && L+R+C != 0)
{
memset(mark, 0, sizeof(mark));
memset(mark, 0, sizeof(matrix));
getchar();
char c;
for(int i = 1;i <= L;i++)
{
for(int j = 1;j <= R;j++)
{
for(int m = 1;m <= C;m++)
{
cin >> c;
matrix[i][j][m] = c;
if(c == 'S')
startz = i, startx = j, starty = m;
}
}
}
/*printf("endscanf\n");
for(int i = 1;i <= L;i++)
{
for(int j = 1;j <= R;j++)
{
for(int m = 1;m <= C;m++)
{
printf("%c", matrix[i][j][m]);
}
printf("\n");
}
printf("\n");
}*/
queue<node> que;
que.push({startx, starty, startz, 0});
mark[startz][startx][starty] = 1;
int flag = 0;
while(!que.empty())
{
node temp = que.front();
que.pop();
if(matrix[temp.z][temp.x][temp.y] == 'E')
{
ans = temp.step;
flag = 1;
break;
}
for(int i = 0;i < 6;i++)
{
int cx = temp.x, cy = temp.y, cz = temp.z;
cx += direction[i][0];
cy += direction[i][1];
cz += direction[i][2];
if(cx <= 0 || cx > R || cy <= 0 || cy > C || cz <= 0 || cz > L)
continue;
if(mark[cz][cx][cy])
continue;
if(matrix[cz][cx][cy] == '.' || matrix[cz][cx][cy] == 'E')
{
mark[cz][cx][cy] = 1;
que.push({cx, cy, cz, temp.step+1});
}
}
}
if(flag)
printf("Escaped in %d minute(s).\n", ans);
else
printf("Trapped!\n");
}
return 0;
}