Acwing 走迷宫 知识点:bfs 三种写法

45 阅读2分钟

844. 走迷宫 - AcWing题库

bfs按层搜索,我们可以看出最短的路径是8

image.png

如果是dfs的话每次会一条路走到底1,每次走的都是随机的,因此很可能最后才走到那条最短的路径=,比较低效:

image.png

image.png

code

#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
typedef pair<int,int>PII;
const int N=110;
int n,m;
int Map[N][N];//存储的地图
int d[N][N];//存储每一个点到终点的举例

int dx[4]={-1,0,1,0};int dy[4]={0,1,0,-1};
int cnt;
int bfs()
{
   queue<PII>q;
   q.push({0,0});//加入起始点
   memset(d,-1,sizeof d);//初始化所有路径为未走过
   d[0][0]=0;//起始点标记为走过了
   
   //开始搜索
   while(!q.empty())//当队列不为空时
   {
       PII t=q.front();
       q.pop();

       
       //按层把元素加入队尾
       for(int i=0;i<4;i++)//枚举四个方向
       {
            int x=t.first+dx[i],y=t.second+dy[i];//开始移动
            if(x>=0&&x<n&&y>=0&&y<m&&Map[x][y]==0&&d[x][y]==-1)//当前位置没有越界,并且是空地且没被走过,才可以接着走
            {
                d[x][y]=d[t.first][t.second]+1;//下一个位置左边=当前位置坐标+110
                q.push({x,y});//加入队尾
            }
       }
      
   }
   return d[n-1][m-1];//返回到达右下角位置的距离
    
}
int main()
{
    cin>>n>>m;
    for(int i=0;i<n;i++)
        for(int j=0;j<m;j++)
        cin>>Map[i][j];
    cout<<bfs()<<endl;
      
    return 0;
}

第二种写法

#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int>PII;
const int N = 110;
int g[N][N];
int vis[N][N];
int dis[N][N];
int n, m;

int dx[] = { -1,0,1,0 }, dy[] = { 0,1,0,-1 };
void dfs(int x, int y)
{
    queue<PII>q;
    q.push({ x,y });
    vis[x][y] = 1;

    while (!q.empty())
    {
        PII t = q.front();
        q.pop();

        for (int i = 0; i < 4; i++)
        {
            int tx = t.first + dx[i], ty = t.second + dy[i];

            //判断是否合法
            if (tx<1 || tx>n || ty<1 || ty>m || vis[tx][ty] == 1 || g[tx][ty] == 1)continue;


            dis[tx][ty] = dis[t.first][t.second] + 1;
            vis[tx][ty] = 1;
            q.push({ tx,ty });
        }

    }
}

int main()
{
    cin >> n >> m;

    for (int i = 1; i <= n; i++)
    {
        for(int j=1;j<=m;j++)
        cin >> g[i][j];
    }

    dfs(1, 1);

    cout << dis[n][m] << endl;
    return 0;
}

手写队列

#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int>PII;
const int N = 110;
int g[N][N];
int vis[N][N];
int dis[N][N];
PII q[N*N];
int n, m;

int dx[] = { -1,0,1,0 }, dy[] = { 0,1,0,-1 };
void dfs(int x, int y)
{
    int hh=0,tt=0;
    q[0]={1,1};
    vis[x][y] = 1;

    while (hh<=tt)
    {
        PII t=q[hh++];

        for (int i = 0; i < 4; i++)
        {
            int tx = t.first + dx[i], ty = t.second + dy[i];

            //判断是否合法
            if (tx<1 || tx>n || ty<1 || ty>m || vis[tx][ty] == 1 || g[tx][ty] == 1)continue;


            dis[tx][ty] = dis[t.first][t.second] + 1;
            vis[tx][ty] = 1;
            q[++tt]={tx,ty};
        }

    }
}

int main()
{
    cin >> n >> m;

    for (int i = 1; i <= n; i++)
    {
        for(int j=1;j<=m;j++)
        cin >> g[i][j];
    }

    dfs(1, 1);

    cout << dis[n][m] << endl;
    return 0;
}