题目描述: https://vjudge.net/problem/POJ-2251

  • 使用bfs来找最短时间
  • 剪枝,本题用了vis数组来存储走过的位置,确保不会重新回到走过的位置,造成爆栈

ac代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <queue>
#include <string.h>
#define MAX 32
using namespace std;

struct position{
int i,j,k,time;
};
char dungeon[MAX][MAX][MAX];
char vis[MAX][MAX][MAX];
queue<position> note;

int main() {
int i,j,k,flag,l,r,c;
position start,end,go,temp;
int mi[]={0,0,0,0,1,-1};
int mj[]={0,0,1,-1,0,0};
int mk[]={1,-1,0,0,0,0};

while(cin>>l>>r>>c && (l!=0 && r!=0 && c!=0)) {
memset(vis,0,sizeof(vis));
for (i = 0; i < l; i++) {
for (j = 0; j < r; j++) {
for (k = 0; k < c; k++) {
cin >> dungeon[i][j][k];
if(dungeon[i][j][k] == 'S'){
start.i = i;start.j = j;start.k = k,start.time=0;
dungeon[i][j][k] = '.';
vis[i][j][k] = 1;
}
if(dungeon[i][j][k] == 'E'){
end.i = i;end.j = j;end.k = k;
dungeon[i][j][k] = '.';
}
}
}
}
note = queue<position>();
note.push(start);
flag = 0;
while(!note.empty()){
go = note.front();
if(go.i==end.i && go.j==end.j && go.k==end.k){
flag = 1;
break;
}
for(i=0;i<6;i++){
temp.i = go.i + mi[i];
temp.j = go.j + mj[i];
temp.k = go.k + mk[i];
temp.time = go.time + 1;
if(temp.i<l && temp.i>=0 && temp.j<r && temp.j>=0 && temp.k < c && temp.k>=0 && !vis[temp.i][temp.j][temp.k] && dungeon[temp.i][temp.j][temp.k]=='.'){
vis[temp.i][temp.j][temp.k] = 1;
note.push(temp);
}
}
note.pop();
}
if(flag)
cout<<"Escaped in "<<go.time<<" minute(s)."<<endl;
else
cout<<"Trapped!"<<endl;
}
return 0;
}