给定一个多层的地牢(多维数组),'.'表示空白格, '#'表示障碍。给定一个起点和终点,可以在空白格移动,可以向上移动,向下移动,向左移动和向右移动,问到达终点的最短路径。
思路:BFS
#include<iostream> #include<queue> using namespace std; typedef struct pos{ int x; int y; int z; }Pos; const int INF = 1000000; int L, R, C; int sx, sy, sz; int fx, fy, fz; char maze[40][40][40]; int d[40][40][40]; int dx[6] = {1, -1, 0, 0, 0, 0}, dy[6] = {0, 0, 0, 0, 1, -1}, dz[6] = {0, 0, -1, 1, 0, 0}; void bfs(int x, int y, int z){ Pos p; p.x = x; p.y = y; p.z = z; queue<Pos> q; q.push(p); d[x][y][z] = 0; while( !q.empty() ){ Pos t = q.front(); q.pop(); for(int i=0; i<6; i++){ int nx = t.x + dx[i]; int ny = t.y + dy[i]; int nz = t.z + dz[i]; if(nx >= 0 && nx < L && ny >= 0 && ny < R && nz >= 0 && nz < C && d[nx][ny][nz] == INF && maze[nx][ny][nz] != '#'){ Pos rel; rel.x = nx; rel.y = ny; rel.z = nz; q.push(rel); d[nx][ny][nz] = d[t.x][t.y][t.z] + 1; } } } } int main(){ ios::sync_with_stdio(false); while(cin >> L >> R >> C){ if(L==0 && R==0 && C==0) break; for(int i=0; i<L; i++){ for(int j=0; j<R; j++){ for(int k=0; k<C; k++){ d[i][j][k] = INF; cin >> maze[i][j][k]; if(maze[i][j][k] == 'S'){ sx = i; sy = j; sz = k; } if(maze[i][j][k] == 'E'){ fx = i; fy = j; fz = k; } } } } bfs(sx, sy, sz); if(d[fx][fy][fz] != INF) cout << "Escaped in " << d[fx][fy][fz] << " minute(s)." << endl; else cout << "Trapped!" << endl; } return 0; }