宽度优先搜索求迷宫最短路模板:

【宽度优先搜索】LeetCode1091二进制矩阵中的最短路径_#define

【宽度优先搜索】LeetCode1091二进制矩阵中的最短路径_散列表_02

 

【宽度优先搜索】LeetCode1091二进制矩阵中的最短路径_蓝桥杯_03

 

给你一个 n x n 的二进制矩阵 grid 中,返回矩阵中最短 畅通路径 的长度。如果不存在这样的路径,返回 -1 。

二进制矩阵中的 畅通路径 是一条从 左上角 单元格(即(0, 0))到 右下角 单元格(即(n - 1, n - 1))的路径,该路径同时满足下述要求:

路径途经的所有单元格都的值都是 0 。
路径中所有相邻的单元格应当在 8 个方向之一 上连通(即,相邻两单元之间彼此不同且共享一条边或者一个角)。
畅通路径的长度 是该路径途经的单元格总数。

 每次有8种选择,套用bfs模板

#define x first
#define y second
typedef pair<int,int> PII;
class Solution {
public:
    int shortestPathBinaryMatrix(vector<vector<int>>& g) {
       if(g[0][0])return -1;
       int n=g.size();
       vector<vector<int>>dist(n,vector<int>(n,-1));
       dist[0][0]=1;
       queue<PII>q;
       q.push({0,0});
       int dx[]={-1,-1,-1,0,1,1,1,0};
       int dy[]={-1,0,1,1,1,0,-1,-1};
       while(q.size()){
           auto t=q.front();
           q.pop();
           for(int i=0;i<8;i++){
               int x=t.x+dx[i],y=t.y+dy[i];
               if(x>=0&&x<n&&y>=0&&y<n&&g[x][y]==0&&dist[x][y]==-1){
                   dist[x][y]=dist[t.x][t.y]+1;
                   q.push({x,y});
               }
           }
       }
       return dist[n-1][n-1];
    }
};
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.