1091. Shortest Path in Binary Matrix
问题:
给定n*n二维数组,要从(0,0)->(n-1,n-1)
- 0:通路
- 1:障碍
求最少多少步能到达。
可以走当前格子的8个方向。
Example 1: Input: grid = [[0,1],[1,0]] Output: 2 Example 2: Input: grid = [[0,0,0],[1,1,0],[1,1,0]] Output: 4 Example 3: Input: grid = [[1,0,0],[1,1,0],[1,1,0]] Output: -1 Constraints: n == grid.length n == grid[i].length 1 <= n <= 100 grid[i][j] is 0 or 1
example 1:
example 2:
解法:BFS
状态:当前格子的坐标(x,y)
选择:当前格子的8个方向:x+dir[-][0], y+dir[-][1]
- vector<vector<int>> dir={{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};
每层展开step++
代码参考:
1 class Solution { 2 public: 3 vector<vector<int>> dir={{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}}; 4 int shortestPathBinaryMatrix(vector<vector<int>>& grid) { 5 int n = grid.size(); 6 int step = 0; 7 queue<pair<int,int>> q; 8 if(grid[0][0]==0 && grid[n-1][n-1]==0) { 9 q.push({0,0}); 10 grid[0][0]=1; 11 } else { 12 return -1; 13 } 14 while(!q.empty()) { 15 int sz = q.size(); 16 step++; 17 for(int i=0; i<sz; i++) { 18 auto[cur_x,cur_y] = q.front(); 19 q.pop(); 20 if(cur_x==n-1 && cur_y==n-1) return step; 21 for(auto d:dir) { 22 int x = cur_x+d[0]; 23 int y = cur_y+d[1]; 24 if(x<0 || y<0 || x>=n || y>=n || grid[x][y]!=0) continue; 25 q.push({x,y}); 26 grid[x][y]=1; 27 } 28 } 29 } 30 return -1; 31 } 32 };