搜索专题 L

来源:互联网 发布:编辑部的故事 知乎 编辑:程序博客网 时间:2024/05/19 00:42

1、简单描述

立体迷宫,问从一个点到另一个点至少走多少步

2、思路

#include <iostream>
#include <string.h>
#include <queue>
#include <algorithm>
using namespace std;
char mp[31][31][31];
int vis[31][31][31];
int k,n,m,sx,sy,sz,ex,ey,ez;
int dir[6][3] = {{0,0,1},{0,0,-1},{0,1,0},{0,-1,0},{1,0,0},{-1,0,0}};
struct node
{
    int x,y,z,step;
};


bool check(int x,int y,int z)
{
    if(x<0 || y<0 || z<0 || x>=k || y>=n || z>=m)
        return true;
    else if(mp[x][y][z] == '#')
        return true;
    else if(vis[x][y][z])
        return true;
    return false;
}
int bfs()
{
    int i;
    node now,next;
    queue<node> Q;
    now.x = sx;
    now.y = sy;
    now.z = sz;
    now.step = 0;
    vis[sx][sy][sz] = true;
    Q.push(now);
    while(!Q.empty())
    {
        now = Q.front();
        Q.pop();
        if(now.x == ex && now.y == ey && now.z == ez)
            return now.step;
        for(i = 0; i<6; i++)
        {
            next = now;
            next.x = now.x+dir[i][0];
            next.y = now.y+dir[i][1];
            next.z = now.z+dir[i][2];
            if(check(next.x,next.y,next.z))
                continue;
            vis[next.x][next.y][next.z] = true;
            next.step = now.step+1;
            Q.push(next);
        }
    }
    return 0;
}


int main()
{
    int i,j,r;
    while(cin>>k>>n>>m&&k+m+n)
    {
        for(i = 0; i<k; i++)
        {
            for(j = 0; j<n; j++)
            {
                cin>>mp[i][j];
                for(r = 0; r<m; r++)
                {
                    if(mp[i][j][r] == 'S')
                    {
                        sx = i,sy = j,sz = r;
                    }
                    else if(mp[i][j][r] == 'E')
                    {
                        ex = i,ey = j,ez = r;
                    }
                }
            }
        }
        memset(vis,0,sizeof(vis));
        int ans;
        ans = bfs();
        if(ans)
            cout<<"Escaped in "<<ans<<" minute(s)."<<endl;
        else
            cout<<"Trapped!"<<endl;
    }
    return 0;
}

跟之前bfs遍历问题相似,只是该题node结点,包含x,y,z;向六个方向搜索。

原创粉丝点击