• 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 };
  • 相关阅读:
    客户端用mstsc不能用一台设备连接终端服务器的解决办法
    [转]知识管理ABC
    Visual Studio常用小技巧[备忘]
    一套外企的数据库设计面试题
    MSDN中的图形元素和文档约定[备忘]
    设计模式概述
    ASP.Net 4.0中新增加的23项功能[转]
    Dreamweaver 8 的相关使用
    浅谈ThreadPool 线程池
    C#委托的异步调用[学习]
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/14537552.html
Copyright © 2020-2023  润新知