题目大意:给一个三维图,可以前后左右上下6种走法,走一步1分钟,求最少时间(其实就是最短路)
分析:这里与二维迷宫是一样的,只是多了2个方向可走,BFS就行(注意到DFS的话复杂度为O(6^n)肯定会TLE)
附上代码:
#include<iostream> #include<algorithm> #include<cstring> #include<queue> using namespace std; #define f(t,from,to) for(int t=from;t<=to;t++) #define clr(arr,val) memset(arr,val,sizeof arr) #define judge(h,x,y) !vis[h][x][y]&&(a[h][x][y]=='.'||a[h][x][y]=='E') struct point { int h, x, y; point(int a = 0, int b = 0, int c = 0){ h = a, x = b, y = c; } }; char a[32][35][35]; bool vis[32][35][35]; int d[32][35][35]; int _move[6][3] = { { 1, 0, 0 }, { -1, 0, 0 }, { 0, 0, 1 }, { 0, 0, -1 }, { 0, 1, 0 }, { 0, -1, 0 } }; int L, n, m, sh, sx, sy, eh, ex, ey; int bfs() { queue<point> q; q.push(point(sh, sx, sy)); vis[sh][sx][sy] = 1; while (!q.empty()) { point v = q.front(); q.pop(); for (int i = 0; i < 6; i++) { int fh = v.h + _move[i][0], fx = v.x + _move[i][1], fy = v.y + _move[i][2]; if (judge(fh, fx, fy)) { vis[fh][fx][fy] = 1; d[fh][fx][fy] = d[v.h][v.x][v.y] + 1; q.push(point(fh, fx, fy)); if (a[fh][fx][fy] == 'E') return d[fh][fx][fy]; } } } return 0x3f3f3f3f; } int main() { while (cin >> L >> n >> m&&L&&n&&m) { int ans; clr(a, false), clr(vis, false), clr(d, 0); f(i, 1, L) f(j, 1, n) f(k, 1, m) { cin >> a[i][j][k]; if (a[i][j][k] == 'S') { sh = i, sx = j, sy = k; } if (a[i][j][k] == 'E') { eh = i, ex = j, ey = k; } } ans = bfs(); if (ans < 0x3f3f3f3f) printf("Escaped in %d minute(s).\n", ans); else printf("Trapped!\n"); } return 0; }