2023-05-29每日一題
一、題目編號
1091. 二進(jìn)制矩陣中的最短路徑
二、題目鏈接
點(diǎn)擊跳轉(zhuǎn)到題目位置
三、題目描述
給你一個 n x n 的二進(jìn)制矩陣 grid 中,返回矩陣中最短 暢通路徑 的長度。如果不存在這樣的路徑,返回 -1 。
二進(jìn)制矩陣中的 暢通路徑 是一條從 左上角 單元格(即,(0, 0))到 右下角 單元格(即,(n - 1, n - 1))的路徑,該路徑同時滿足下述要求:
- 路徑途經(jīng)的所有單元格都的值都是 0 。
- 路徑中所有相鄰的單元格應(yīng)當(dāng)在 8 個方向之一 上連通(即,相鄰兩單元之間彼此不同且共享一條邊或者一個角)。
暢通路徑的長度 是該路徑途經(jīng)的單元格總數(shù)。
四、解題代碼
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方向遍歷,這用一維數(shù)組控制也可以,但是習(xí)慣上用二維數(shù)組來控制。
(2) 使用廣度優(yōu)先搜索來進(jìn)行遍歷,從(0,0)點(diǎn)開始遍歷。利用隊(duì)列+哈希的形式來進(jìn)行廣搜。首先得判斷,(0,0)點(diǎn)是否為0和是否只有(0,0)點(diǎn)并且為0。文章來源:http://www.zghlxwxcb.cn/news/detail-461053.html
(3) 廣搜在平面的壓入隊(duì)列條件為不越界,哈希未標(biāo)記,并且為0,并且可以通過提前判斷是否到(m-1, n-1)來結(jié)束廣度優(yōu)先搜索。文章來源地址http://www.zghlxwxcb.cn/news/detail-461053.html
到了這里,關(guān)于2023-5-26 LeetCode每日一題(二進(jìn)制矩陣中的最短路徑)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!