这题是一道简单的广搜题目,读入的时候,需要注意,如果是用scanf读入的话,就直接读取每行的字符串,不然的话,行尾的回车,也会被当成字符读入,这样的话,每次读取的数目就会小于我们想要的数目,因为每次把回车当成迷宫读入了嘛。
所以如果直接读入一个字符串的话,我们就把回车一并读入,但是不用它就可以了。
如果是用cin读入的话,我们就可以用三重循环读入每一个字符,cin会自动跳过空白符。
还有就是cin即使关闭和stdio的同步,也依旧可以和stdio混用。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int maze[35][35][35];
int vis[35][35][35];
int sl, sr, sc, el, er, ec, L, R, C;
int d[6][3]={{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};
struct Step {
int l, r, c, step;
};
int check(int i,int j,int k)
{
if (i<0||j<0||k<0||i>=L||j>=R||k>=C)
return 1;
if (maze[i][j][k]==0)
return 1;
if (vis[i][j][k])
return 1;
return 0;
}
int bfs()
{
queue<Step> q;
vis[sl][sr][sc] = 1;
Step head,next;
head.l = sl;
head.r = sr;
head.c = sc;
head.step = 0;
q.push(head);
while (!q.empty()) {
Step a = q.front();
q.pop();
if (a.l==el&&a.r==er&&a.c==ec)
return a.step;
for (int i = 0; i < 6;i++) {
next.l = a.l + d[i][0];
next.r = a.r + d[i][1];
next.c = a.c + d[i][2];
if (check(next.l,next.r,next.c))
continue;
vis[next.l][next.r][next.c] = 1;
next.step = a.step + 1;
q.push(next);
}
}
return 0;
}
int main()
{
char ch;
ios::sync_with_stdio(false);
while (cin>>L>>R>>C&&L+R+C) {
memset(maze, 0, sizeof(maze));
memset(vis, 0, sizeof(vis));
for (int i = 0; i < L;i++) {
for (int j = 0; j < R;j++) {
for (int k = 0; k < C;k++) {
cin >> ch;
if (ch=='.') {
maze[i][j][k] = 1;
}
else if (ch=='S') {
sl = i, sr = j, sc = k;
maze[i][j][k] = 1;
}
else if (ch=='E') {
el = i, er = j, ec = k;
maze[i][j][k] = 1;
}
}
}
}
int min = bfs();
if (min)
printf("Escaped in %d minute(s).
", min);
else
printf("Trapped!
");
// if (min)
// cout << "Escaped in " << min << " minute(s)." << endl;
// else
// cout << "Trapped!" << endl;
}
return 0;
}