POJ 2251 Dungeon Master(bfs)

44 篇文章 0 订阅
39 篇文章 0 订阅

简单的BFS模版题。   重新审视BFS和DFS以及DP,发现三者之间存在莫大关联,总的来说,都是对状态的深入理解,以及记录状态再利用,利用状态扩展其他可能状态,以及利用状态剪枝 。   

细节参见代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<set>
#include<cmath>
#include<queue>
using namespace std;
typedef long long ll;
const int mod = 1000000007;
const int INF = 1000000000;
const int maxn = 35;
int l,r,c,d[maxn][maxn][maxn];
struct node{
    int x,y,z;
    node(int x=0,int y=0,int z=0):x(x),y(y),z(z) {}
    bool operator == (const node& rhs) const {
        return x == rhs.x && y == rhs.y && z == rhs.z;
    }
}S,E;
int dz[] = { 0,0,0,0,1,-1 };
int dx[] = { 0,1,0,-1,0,0 };
int dy[] = { 1,0,-1,0,0,0 };
char s[maxn][maxn][maxn];
int bfs(node S) {
    queue<node> q;
    q.push(S);
    memset(d,-1,sizeof(d));
    d[S.z][S.x][S.y] = 0;
    while(!q.empty()) {
        node u = q.front(); q.pop();
        if(u == E) return d[u.z][u.x][u.y];
        for(int i=0;i<6;i++) {
            int x = u.x+dx[i], y = u.y+dy[i], z = u.z+dz[i];
            if(z < 1 || z > l || x < 1 || x > r || y < 1 || y > c) continue;
            node v = node(x,y,z);
            if(s[z][x][y] == '.' && d[z][x][y] == -1) {
                d[z][x][y] = d[u.z][u.x][u.y] + 1;
                q.push(v);
            }
        }
    }
    return -1;
}
int main() {
    while(~scanf("%d%d%d",&l,&r,&c)) {
        if(!l && !r && !c) return 0;
        for(int i=1;i<=l;i++) 
            for(int j=1;j<=r;j++) scanf("%s",s[i][j]+1);
        for(int i=1;i<=l;i++) 
            for(int j=1;j<=r;j++) 
                for(int k=1;k<=c;k++) 
                    if(s[i][j][k] == 'S') S = node(j,k,i), s[i][j][k] = '.';
                    else if(s[i][j][k] == 'E') E = node(j,k,i), s[i][j][k] = '.';
        int ans = bfs(S);
        if(ans == -1) printf("Trapped!\n");
        else printf("Escaped in %d minute(s).\n",ans);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值