解救小明 BFS

解救小明:

利用广搜BFS
有一天小明一个人去玩迷宫,但是方向感不好的小明迷路了,小红得知后要去解救小明,小红知道了迷宫的地图,小红要以最快的速度解救小哈
迷宫由m行n列组成,都小于50,每个单元格要不是空地,要不是障碍物,你的任务是帮助小红找到一条通往小明的最短路径,注意障碍物是不能走的。
小明的位置为(p,q),迷宫入口为(1,1),输入数据如下:
5 4
0 0 1 0
0 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
1 1 4 3

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
queue<int>x;//使用三个队列,分别存储X,Y,STEP 
queue<int>y;
queue<int>step;
int flag=0,m,n,p,q;
int a[51][51],book[51][51];
void bfs()
{
    int next[4][2]={{0,1},{1,0},{-1,0},{0,-1}};
    int tx,ty,k;
    while(!x.empty())
    {
        for(int i=0;i<4;i++)
        {
            tx=x.front()+next[i][0];
            ty=y.front()+next[i][1];
            if(tx>0&&tx<=m&&ty>0&&ty<=n)
            {
                if(a[tx][ty]==0&&book[tx][ty]==0)
                {
                    book[tx][ty]=1;
                    x.push(tx);
                    y.push(ty);
                    step.push(step.front() +1);
                }
            }
            if(tx==p&&ty==q)
            {
                flag=1;
                break;
            }
        }
        x.pop();    
        y.pop();
        step.pop();
    }
    if(flag==1)
    {
        return;
    }
}
int main(){
    int startx,starty;
    scanf("%d%d",&m,&n);
    for(int i=1;i<=m;i++)
    {
        for(int j=1;j<=n;j++)
        {
            scanf("%d",&a[i][j]);
        }
    }
    scanf("%d%d%d%d",&startx,&starty,&p,&q);
    x.push(startx);
    y.push(starty);
    step.push(0);
    book[startx][starty]=1;
    bfs();
    printf("%d",step.back());
    return 0;
}

利用DFS :https://blog.csdn.net/qq_42866708/article/details/81533575

猜你喜欢

转载自blog.csdn.net/qq_42866708/article/details/81534345
BFS