B - Dungeon Master (vj)

其实跟之前那篇bfs求最短路类似,只不过那是二维的,而这道题是三维的。


#include<bits/stdc++.h>
using namespace std;
struct node
{
    int x,y,z;
    int cnt;
};
char Map[35][35][35];
int visit[35][35][35];
int dir[6][3]={{0,0,1},{0,0,-1},{0,1,0},{0,-1,0},{1,0,0},{-1,0,0}};
int l,r,c;
int x1,y1,z1;
void bfs()
{
    queue<node>Q;
    node t;
    t.x=x1,t.y=y1,t.z=z1,t.cnt=0;
    visit[x1][y1][z1]=1;
    Q.push(t);
    while(!Q.empty())
    {
        node res=Q.front();
        Q.pop();
        int xx=res.x;
        int yy=res.y;
        int zz=res.z;
        int cnt=res.cnt;
        if(Map[xx][yy][zz]=='E')
        {
            cout<<"Escaped in "<<cnt<<" minute(s)."<<endl;
            return ;
        }
        for(int i=0;i<6;i++)
        {
            node temp;
            int newx=temp.x=xx+dir[i][0];
            int newy=temp.y=yy+dir[i][1];
            int newz=temp.z=zz+dir[i][2];
            temp.cnt=cnt+1;
            if(newx<1||newx>l||newy<1||newy>r||newz<1||newz>c)
                continue;//边界判断
            if(Map[newx][newy][newz]!='#'&&!visit[newx][newy][newz])
            {
                visit[newx][newy][newz]=1;
                Q.push(temp);
            }
        }
    }
    cout<<"Trapped!"<<endl;
}
int main()
{
    while(cin>>l>>r>>c&&(l||r||c))
    {
        for(int i=1; i<=l; i++)
            for(int j=1; j<=r; j++)
                for(int k=1; k<=c; k++)
                {
                    cin>>Map[i][j][k];//用cin方便处理
                    if(Map[i][j][k]=='S')
                        x1=i,y1=j,z1=k;
                }
        memset(visit,0,sizeof(visit));
        bfs();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41061455/article/details/80344735