2023-5-26 LeetCode每日一题(二进制矩阵中的最短路径)
2023-05-29每日一题
一、题目编号
1091. 二进制矩阵中的最短路径
二、题目链接
点击跳转到题目位置
三、题目描述
给你一个 n x n 的二进制矩阵 grid 中,返回矩阵中最短 畅通路径 的长度。如果不存在这样的路径,返回 -1 。
二进制矩阵中的 畅通路径 是一条从 左上角 单元格(即,(0, 0))到 右下角 单元格(即,(n - 1, n - 1))的路径,该路径同时满足下述要求:
- 路径途经的所有单元格都的值都是 0 。
- 路径中所有相邻的单元格应当在 8 个方向之一 上连通(即,相邻两单元之间彼此不同且共享一条边或者一个角)。
畅通路径的长度 是该路径途经的单元格总数。
四、解题代码
class Solution {int dir[8][2] = {{-1, 0},{1, 0},{0, 1},{0, -1},{1, -1},{1, 1},{-1, -1},{-1, 1},};public:int shortestPathBinaryMatrix(vector<vector<int>>& grid) {queue<int> q;if(grid[0][0] == 1){return -1;}q.push(0 * 110 + 0);int m = grid.size();int n = grid[0].size();if(m == 1 && n == 1){if(grid[0][0] == 0){return 1;}}int hash[12000];memset(hash, 0, sizeof(hash));int cnt = 0;while(!q.empty()){++cnt;int len = q.size();for(int i = 0; i < len; ++i){int node = q.front();q.pop();int x = node / 110;int y = node % 110;for(int j = 0; j < 8; ++j){int next_x = x + dir[j][0];int next_y = y + dir[j][1];if(next_x < 0 || next_x >= m || next_y < 0 || next_y >= n || hash[next_x * 110 + next_y]){continue;}if(grid[next_x][next_y] == 1){if(next_x == m-1 && next_y == n-1){return -1;}continue;}if(next_x == m-1 && next_y == n-1){return cnt + 1;}hash[next_x * 110 + next_y] = 1;q.push(next_x * 110 + next_y);}}}return -1;}
};
五、解题思路
(1) 该问题有8个方向,那么这到题目就要利用到平面的8方向遍历,这用一维数组控制也可以,但是习惯上用二维数组来控制。
(2) 使用广度优先搜索来进行遍历,从(0,0)点开始遍历。利用队列+哈希的形式来进行广搜。首先得判断,(0,0)点是否为0和是否只有(0,0)点并且为0。
(3) 广搜在平面的压入队列条件为不越界,哈希未标记,并且为0,并且可以通过提前判断是否到(m-1, n-1)来结束广度优先搜索。