POJ-2251 Dungeon Master bfs搜索
就是将普通的二维推广到三维,方向变成了六个。
代码如下:
#include <cstring> #include <cstdio> #include <cstdlib> using namespace std; int L, N, M, sx, sy, sz; struct Node { int x, y, z, t; }e[100005], pos; int front, tail, dir[6][3] ={ 0, 1, 0, 0, -1, 0, 1, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, -1 }; // 六个方向,三个坐标 char G[35][35][35]; bool judge(int x, int y, int z) { if (x < 1 || x > N || y < 1 || y > M || z < 1 || z > L) { return false; } else { return true; } } int bfs() { int xx, yy, zz; front = 0; tail = 1; e[tail].x = sx, e[tail].y = sy; e[tail].z = sz,e[tail].t = 0; while (front != tail) { pos = e[++front]; for (int i = 0; i < 6; ++i) { xx = pos.x + dir[i][0]; yy = pos.y + dir[i][1]; zz = pos.z + dir[i][2]; if (judge(xx, yy, zz)) { if (G[zz][xx][yy] == '.') { ++tail; e[tail].x = xx, e[tail].y = yy; e[tail].z = zz, e[tail].t = pos.t + 1; G[zz][xx][yy] = '#'; } else if (G[zz][xx][yy] == 'E') { return pos.t + 1; } } } } return -1; } int main() { int flag, ans; while (scanf("%d %d %d", &L, &N, &M), L|N|M) { flag = 0; for (int i = 1; i <= L; ++i) { for (int j = 1; j <= N; ++j) { scanf("%s", G[i][j]+1); for (int k = 1; k <= M && !flag; ++k) { if (G[i][j][k] == 'S') { sx = j, sy = k, sz = i; G[i][j][k] = '#'; flag = 1; break; } } } } ans = bfs(); if (ans == -1) { printf("Trapped!\n"); } else { printf("Escaped in %d minute(s).\n", ans); } } return 0; }