POJ 2251 Dungeon Master(bfs)

来源:互联网 发布:采购业务数据字典 编辑:程序博客网 时间:2024/05/21 11:02

简单的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