题目链接
http://poj.org/problem?id=2251
题意 给出一个三维地图 给出一个起点 和 一个终点
‘#’ 表示 墙 走不通 ‘.’ 表示 路 可以走通
求 从起点到终点的 最短路径 走不通输出 Trapped!
方向 是可以 上,下,东南西北 六个方向
思路
BFS板子题 注意要记录 S 和 E 的位置 因为不一定是固定的 要标记访问
AC代码
#include <cstdio> #include <cstring> #include <ctype.h> #include <cstdlib> #include <cmath> #include <climits> #include <ctime> #include <iostream> #include <algorithm> #include <deque> #include <vector> #include <queue> #include <string> #include <map> #include <stack> #include <set> #include <list> #include <numeric> #include <sstream> #include <iomanip> #include <limits> #define CLR(a, b) memset(a, (b), sizeof(a)) #define pb push_back using namespace std; typedef long long ll; typedef long double ld; typedef unsigned long long ull; typedef pair <int, int> pii; typedef pair <ll, ll> pll; typedef pair<string, int> psi; typedef pair<string, string> pss; const double PI = acos(-1.0); const double E = exp(1.0); const double eps = 1e-8; const int INF = 0x3f3f3f3f; const int maxn = 3e1 + 5; const int MOD = 1e9 + 7; int G[maxn][maxn][maxn]; int v[maxn][maxn][maxn]; int sx, sy, sz, ex, ey, ez; int Move[6][3] { 1, 0, 0, -1, 0, 0, 0, 1, 0, 0,-1, 0, 0, 0, 1, 0, 0,-1, }; struct node { int x, y, z; int step; }; int ans; int c, n, m; bool ok(int x, int y, int z) { if (x < 0 || x >= c || y < 0 || y >= n || z < 0 || z >= m || G[x][y][z] || v[x][y][z]) return false; return true; } void bfs() { node tmp; tmp.x = sx; tmp.y = sy; tmp.z = sz; tmp.step = 0; queue <node> q; q.push(tmp); v[sx][sy][sz] = 1; while (!q.empty()) { node u = q.front(), V; q.pop(); if (u.x == ex && u.y == ey && u.z == ez) { ans = u.step; return; } for (int i = 0; i < 6; i++) { V.x = u.x + Move[i][0]; V.y = u.y + Move[i][1]; V.z = u.z + Move[i][2]; if (ok(V.x, V.y, V.z)) { V.step = u.step + 1; q.push(V); v[V.x][V.y][V.z] = 1; } } } } int main() { while (scanf("%d%d%d", &c, &n, &m) && (c || n || m)) { CLR(G, 0); CLR(v, 0); string s; for (int i = 0; i < c; i++) { for (int j = 0; j < n; j++) { cin >> s; for (int k = 0; k < m; k++) { if (s[k] == 'S') { sx = i; sy = j; sz = k; G[i][j][k] = 0; } else if (s[k] == 'E') { ex = i; ey = j; ez = k; G[i][j][k] = 0; } else if (s[k] == '.') G[i][j][k] = 0; else if (s[k] == '#') G[i][j][k] = 1; } } } ans = -1; bfs(); if (ans == -1) printf("Trapped!\n"); else printf("Escaped in %d minute(s).\n", ans); } }转载于:https://www.cnblogs.com/Dup4/p/9433115.html
相关资源:JAVA上百实例源码以及开源项目