题目链接:POJ 2251
题意:迷宫问题。
分析:
二维变三维,BFS。注意存储下标含义即可。
a[j][k][i] = s[k];
if (s[k] == 'S')
{sx = j, sy = k, sz = i;//i相当于z轴,对应L;j相当于x轴,对应C;k相当于y轴,对应R
}
else if (s[k] == 'E')
{ex = j, ey = k, ez = i;
}
CODE:
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;const int maxn = 31;
char s[maxn], a[maxn][maxn][maxn];
int vis[maxn][maxn][maxn];
int dir[6][3] = { {0,0,1},{0,1,0},{1,0,0},{-1,0,0},{0,-1,0},{0,0,-1} };
int sx, sy, sz, ex, ey, ez, L, R, C;struct Node {int x, y, z;int step;
}cur,nextnode;int valid(int x, int y, int z)
{if (x < 0 || y < 0 || z < 0 || x >= R || y >= C || z >= L) return 0;//下标越界if (vis[x][y][z] == 1) return 0;//访问过该点if (a[x][y][z] == '#') return 0;//遇到墙return 1;
}
int bfs()
{queue<Node> q;cur.x = sx, cur.y = sy, cur.z = sz;cur.step = 0;q.push(cur);vis[sx][sy][sz] = 1;while (!q.empty()){cur = q.front();q.pop();for (int i = 0;i < 6;i++){nextnode.x = cur.x + dir[i][0];nextnode.y = cur.y + dir[i][1];nextnode.z = cur.z + dir[i][2];nextnode.step = cur.step + 1;if (!valid(nextnode.x, nextnode.y, nextnode.z)) continue;if (nextnode.x == ex&&nextnode.y == ey&&nextnode.z == ez) return nextnode.step;//找到出口vis[nextnode.x][nextnode.y][nextnode.z] = 1;//cout << nextnode.x << " " << nextnode.y << " " << nextnode.z << endl;q.push(nextnode);}}return -1;
}int main()
{
#ifdef LOCALfreopen("in.txt", "r", stdin);freopen("out.txt", "w", stdout);
#endifwhile (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++){cin >> s;for (int k = 0;k < C;k++){a[j][k][i] = s[k];if (s[k] == 'S'){sx = j, sy = k, sz = i;//cout << sx << " " << sy << " " << sz << endl;}else if (s[k] == 'E'){ex = j, ey = k, ez = i;//cout << ex << " " << ey << " " << ez << endl;}}}}/*for (int i = 0;i < L;i++){for (int j = 0;j < R;j++)puts(a[i][j]);putchar('\n');}*/memset(vis, 0, sizeof(vis));int ans = bfs();if (ans == -1) cout<<"Trapped!" << endl;else printf("Escaped in %d minute(s).\n", ans);}return 0;
}