poj 2251 三维地图最短路径问题 bfs算法

时间:2023-03-09 18:25:09
poj  2251 三维地图最短路径问题 bfs算法

题意:给你一个三维地图,然后让你走出去,找到最短路径。

思路:bfs

  1. 每个坐标的表示为 x,y,z并且每个点都需要加上时间 t

    struct node
    {
    int x, y, z;
    int t;
    };

  2. bfs用队列,进队列的时候要标记,并且 t+1;
  3. 最先到达终点的,所花的时间必定最短

代码上的小技巧:
三维地图需要你去遍历的时候需要走六个方向:

int dx[] = { ,,,,,- };
int dy[] = { ,,-,,, };
int dz[] = { ,-,,,, };

解决问题的代码:

#include <cstdio>
#include <iostream>
#include <queue>
#include <algorithm>
#include <cstring>
using namespace std;
int r, n, m;
string s[][];
struct node
{
int x, y, z;
int t;
};
node Begin, End;
queue <node> que;
int dx[] = { ,,,,,- };
int dy[] = { ,,-,,, };
int dz[] = { ,-,,,, };
int vis[][][];
int bfs()
{
que.push(Begin);
vis[Begin.x][Begin.y][Begin.z] = ;
while (!que.empty())
{
node front = que.front();
que.pop();
if (front.x == End.x && front.y == End.y && front.z == End.z) return front.t;
for (int i = ; i < ; i++)
{
node tmp;
tmp.x = front.x + dx[i];
tmp.y = front.y + dy[i];
tmp.z = front.z + dz[i];
tmp.t = front.t + ;
if (tmp.x >= && tmp.x < r && tmp.y >= && tmp.y < n && tmp.z >= && tmp.z < m && !vis[tmp.x][tmp.y][tmp.z] && s[tmp.x][tmp.y][tmp.z] != '#')
{
que.push(tmp);
vis[tmp.x][tmp.y][tmp.z] = ;
}
}
}
return -;
}
int main()
{
while (cin >> r >> n >> m)
{
if (r == && n == && m == ) break;
memset(vis, , sizeof(vis));
while (!que.empty())
{
que.pop();
}
for (int i = ; i < r; i++) {
string ret;
for (int j = ; j < n; j++) {
cin >> s[i][j];
for (int k = ; k < m; k++) {
if (s[i][j][k] == 'S') {
Begin.x = i, Begin.y = j, Begin.z = k; Begin.t = ;
}
else if (s[i][j][k] == 'E') {
End.x = i, End.y = j, End.z = k; End.t = ;
}
}
}
}
int ans = bfs();
if (ans == -) {
printf("Trapped!\n");
}
else {
printf("Escaped in %d minute(s).\n", ans);
}
} return ;
}