bfs模板 走迷宫acwing

#include 
#include 
#include 

using namespace std;

typedef pair PII;

const int N = 110;
int n, m;
int g[N][N], d[N][N];
PII q[N * N];

int bfs()
{
    //init queue
    q[0] = {0, 0};
    int hh = 0, tt = 0;
    
    //init distance
     memset(d, -1, sizeof d);
     d[0][0] = 0;
     
     //定义方向数组
     int dx[4] = {0, -1, 0, 1};
     int dy[4] = {-1, 0, 1, 0};
     
     //开始宽搜
     while (hh <= tt)
     {
         //获取队首元素
         auto t = q[hh ++ ]; 
         //先获取 后++
         
         for (int i = 0; i < 4; i ++ )
         {
             int x = t.first + dx[i];
             int y = t.second + dy[i];
             
             if (x >= 0 && x < n && y >= 0 && y < m) //边界内
                if (g[x][y] == 0 && d[x][y] == -1) //点可达且未到达过
                {
                    d[x][y] = d[t.first][t.second] + 1; //更新能到点的距离
                    q[++ tt] = {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 >> g[i][j];
            
    cout << bfs() << endl;
    
    return 0;
}

你可能感兴趣的:(宽度优先,算法,c++)