【每日一题】Dungeon Master

Dungeon Master

题意:

一个3D迷宫,‘S’为起点,‘E’为终点,‘.’为路,‘#’为墙,六个方向都可以走(上下左右前后)。问几步到终点?

题解:

简单的搜索问题,没有什么建议。

个人问题:

这个题我卡了3个小时吧。原因在于晕3D,我把x,y,z的意义搞混了,我服了哦!所以如果你卡题了,就看看你的坐标有问题吗?然后看看判断条件是不是有问题(应该是!=#,有些还会写成==’.’)。另外,如果不是熟练掌握搜索的话,用深搜会时间超时,用广搜就没问题了

代码:
///Dungeon Master
#include<iostream>
#include<cstdlib>
#include<string>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<stack>
#include<queue>
#include<iomanip>
#include<map>
#include<set>
#include<functional>
using namespace std;
struct dataa {
    int x, y, z,k;
}now, well;
int a, b, c,s = 0, mink = 100;
int flag[50][50][50];
char brr[50][50][50] , cao;
int dis[6][3] = {{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};///可以走的几个方向
int BFS(dataa A){
    memset(flag, 0, sizeof(flag));///标记点是否走过的地图
    A.k = 0;///初始化
    queue<dataa> Q;
    Q.push(A);///恶梦的开始
    flag[A.x][A.y][A.z] = -1;///标记初始点已经走过了
    while (!Q.empty()) {
        now = Q.front();///处理第一个数据 
        Q.pop();///抛弃第一个数据
        if (brr[now.x][now.y][now.z] == 'E')///判断是否到达目的地
            return now.k;
        for (int i = 0; i < 6; i++) {
            well.x = now.x + dis[i][0];
            well.y = now.y + dis[i][1];
            well.z = now.z + dis[i][2];
            if (well.x >= 0 && well.x < c && well.y >= 0 && well.y < b && well.z >= 0 && well.z < a && brr[well.x][well.y][well.z] != '#' && flag[well.x][well.y][well.z] == 0) {
                well.k = now.k + 1;///总步数加1
                 flag[well.x][well.y][well.z] = well.k;///标记初始点已经走过了,顺便标记这个点是第几步走的
                 Q.push(well);///压进队列
            }
        }
    }
    return -1;
}
int main(){
    while (cin >> c >> b >> a && a&& b&& c) {
        for (int i = 0; i < c; i++) 
            for (int j = 0; j < b; j++) 
                cin >> brr[i][j];
        dataa A;
        for (int i = 0; i < c; i++) 
            for (int j = 0; j < b; j++) 
                for (int k = 0; k < a; k++) 
                    if (brr[i][j][k] == 'S') {A.x = i;A.y = j;A.z = k;}
        int s = BFS(A);
        if (s == -1) cout << "Trapped!" << endl;
        else cout << "Escaped in " << s << " minute(s)." << endl;
    }
    return 0;
}
写在最后:

推荐两篇博客个人关于搜索的总结关于这个题一位同学的题解。这个题的方法相似度很高,而且基本就是模板题。

发布了41 篇原创文章 · 获赞 16 · 访问量 1462

猜你喜欢

转载自blog.csdn.net/weixin_43824551/article/details/104500253