题目链接:https://vjudge.net/problem/POJ-2251
题目描述:给定一个长宽高分别为R、C、L的立体空间,S代表起点,E表示终点,"."表示可通过,"#"表示不可通过,每次可从当前坐标向前后左右上下六个方向移动,但是不可以对角移动。求起点到终点最短路,若不可达,输出“Trapped!”。
思路;BFS常适用于搜索最短路径的解,BFS过程中搜索到的解一定是离根最近的,即最优解。DFS常适用于搜索全部的解。显然,本题比较适合用BFS,至于代码,跟着BFS模板的套路走就好,注意处理细节问题。详细注释说明见代码。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<cstdlib>
#include<sstream>
#include<deque>
#include<stack>
#include<set>
#include<map>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const double eps = 1e-6;
const int maxn = 33;
const int mod = 10;
const int dx[] = {1, -1, 0, 0};
const int dy[] = {0, 0, -1, 1};
const int Dis[] = {-1, 1, -5, 5};
const double inf = 0x3f3f3f3f;
int n, m, k;
int ans;
char g[maxn][maxn][maxn];
bool vis[maxn][maxn][maxn];
struct point{//标记每个点的三维坐标及从起点到达该点需要多长时间
int l, r, c;
int num;
};
bool judge(int l, int r, int c){
return r >= 0 && r < n && c >= 0 && c < m && l >= 0 && l < k;//判断点是否越界
}
int bfs(point beg){
queue<point> que;
que.push(beg);
vis[beg.l][beg.r][beg.c] = true;//标记某个位置是否访问过
int rr, cc;
while(!que.empty()){
point now = que.front(); que.pop();
int l = now.l, r = now.r, c = now.c;
// cout << l << " " << r << " " << c << " " << now.num << " ** " << g[l][r][c] << endl;
if(g[l][r][c] == 'E'){//到达终点,返回时间
return now.num;
}
for(int i = 0; i < 4; ++i){//从当前点向前后左右移动
rr = r + dx[i]; cc = c + dy[i];
if(judge(l, rr, cc) && !vis[l][rr][cc] && g[l][rr][cc] != '#'){//该点未越界、未访问过且可以通行
point next;
next.r = rr; next.c = cc;
next.l = l; next.num = now.num + 1;//记录该点相关信息,加入队列中
que.push(next);
vis[l][rr][cc] = true;//标记该点已访问过
}
}
if(judge(l - 1, r, c) && !vis[l - 1][r][c] && g[l - 1][r][c] != '#'){//向上移动
point next;
next.r = r; next.c = c;
next.l = l - 1; next.num = now.num + 1;
que.push(next);
vis[l - 1][r][c] = true;
}
if(judge(l + 1, r, c) && !vis[l + 1][r][c] && g[l + 1][r][c] != '#'){//向下移动
point next;
next.r = r; next.c = c;
next.l = l + 1; next.num = now.num + 1;
que.push(next);
vis[l + 1][r][c] = true;
}
}
return -1;//若不可达,返回-1
}
int main(){
while(~scanf("%d%d%d", &k, &n, &m) && (k || n || m)){
point beg, aim;
for(int kk = 0; kk < k; ++kk){
getchar();
for(int i = 0; i < n; ++i){
for(int j = 0; j < m; ++j){
scanf("%c", &g[kk][i][j]);
if(g[kk][i][j] == 'S'){//记录起点信息
beg.l = kk, beg.r = i, beg.c = j; beg.num = 0;
}
}
getchar();
}
}
memset(vis, false, sizeof vis);
int ans = bfs(beg);//从起点开始广搜
if(ans == -1) printf("Trapped!\n");
else printf("Escaped in %d minute(s).\n", ans);
}
return 0;
}
该博客介绍了POJ-2251 Dungeon Master问题,这是一个在长宽高为R*C*L的三维空间中,使用BFS寻找起点S到终点E最短路径的问题。博主分享了题目的链接,并指出BFS适用于寻找最短路径,而DFS则用于搜索所有解。他们提供了包含详细注释的BFS解决方案,强调在实现时要注意处理细节。
&spm=1001.2101.3001.5002&articleId=77163783&d=1&t=3&u=61317cec08c843618a108f7b7089898c)
1088

被折叠的 条评论
为什么被折叠?



