题目大意:给一个三维迷宫,给出入口和出口,找出最短路径。
无权图上的单源最短路问题,使用BFS解决。
1 #include <cstdio> 2 #include <queue> 3 #include <cstring> 4 using namespace std; 5 #define MAXN 35 6 7 const int dir[5][2] = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}, {-1, 1}}; 8 int G[MAXN][MAXN][MAXN], dist[MAXN*MAXN*MAXN]; 9 int L, R, C; 10 int s, e; 11 12 int bfs() 13 { 14 queue<int> q; 15 memset(dist, -1, sizeof(dist)); 16 q.push(s); 17 dist[s] = 0; 18 while (!q.empty()) 19 { 20 int u = q.front(); 21 q.pop(); 22 int l = u / (R*C); 23 int r = (u%(R*C)) / C; 24 int c = (u%(R*C)) % C; 25 for (int i = 0; i < 4; i++) 26 { 27 int rr = r + dir[i][0]; 28 int cc = c + dir[i][1]; 29 int v = l*(R*C) + rr*C + cc; 30 if (rr >= 0 && rr < R && cc >= 0 && cc < C && G[l][rr][cc] && dist[v] == -1) 31 { 32 q.push(v); 33 dist[v] = dist[u] + 1; 34 if (v == e) return dist[e]; 35 } 36 } 37 for (int i = 0; i < 2; i++) 38 { 39 int ll = l + dir[4][i]; 40 int v = ll*(R*C) + r*C + c; 41 if (ll >= 0 && ll < L && G[ll][r][c] && dist[v] == -1) 42 { 43 q.push(v); 44 dist[v] = dist[u] + 1; 45 if (v == e) return dist[e]; 46 } 47 } 48 } 49 return dist[e]; 50 } 51 52 int main() 53 { 54 #ifdef LOCAL 55 freopen("in", "r", stdin); 56 #endif 57 char str[100]; 58 while (scanf("%d%d%d", &L, &R, &C) && (L || R || C)) 59 { 60 getchar(); 61 for (int k = 0; k < L; k++) 62 { 63 for (int i = 0; i < R; i++) 64 { 65 gets(str); 66 for (int j = 0; j < C; j++) 67 { 68 if (str[j] == '.') G[k][i][j] = 1; 69 else if (str[j] == '#') G[k][i][j] = 0; 70 else if (str[j] == 'S') 71 { 72 s = k*(R*C) + i*C + j; 73 G[k][i][j] = 1; 74 } 75 else if (str[j] == 'E') 76 { 77 e = k*(R*C) + i*C + j; 78 G[k][i][j] = 1; 79 } 80 } 81 } 82 gets(str); 83 } 84 int ans = bfs(); 85 if (ans > 0) printf("Escaped in %d minute(s). ", ans); 86 else if (ans == -1) printf("Trapped! "); 87 } 88 return 0; 89 }