生活随笔
收集整理的這篇文章主要介紹了
LeetCode 286. 墙与门(BFS)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
1. 題目
你被給定一個 m × n 的二維網格,網格中有以下三種可能的初始化值:
- -1 表示墻或是障礙物
- 0 表示一扇門
- INF 無限表示一個空的房間。然后,我們用 231 - 1 = 2147483647 代表 INF。你可以認為通往門的距離總是小于 2147483647 的。
你要給每個空房間位上填上該房間到 最近 門的距離,如果無法到達門,則填 INF 即可。
示例:
給定二維網格:
INF
-1 0 INF
INF INF INF
-1
INF
-1 INF
-10 -1 INF INF
運行完你的函數后,該網格應該變成:
3 -1 0 12 2 1 -11 -1 2 -10 -1 3 4
來源:力扣(LeetCode) 鏈接:https://leetcode-cn.com/problems/walls-and-gates
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 解題
2.1 BFS 超時解
class Solution {
public:void wallsAndGates(vector
<vector
<int>>& rooms
) {if(rooms
.size()==0 || rooms
[0].size()==0) return;int INF
= INT_MAX
, i
, j
, k
,step
,size
,x
,y
,nx
,ny
;int m
= rooms
.size(), n
= rooms
[0].size();vector
<vector
<int>> dir
= {{1,0},{0,1},{0,-1},{-1,0}};for(i
= 0; i
< m
; ++i
){for(j
= 0; j
< n
; ++j
){if(rooms
[i
][j
]!=INF
)continue;vector
<vector
<bool>> visited(m
, vector
<bool>(n
,false));visited
[i
][j
] = true;queue
<vector
<int>> q
;q
.push({i
,j
});step
= 0;bool found
= false;while(!q
.empty()){size
= q
.size();while(size
--){x
= q
.front()[0];y
= q
.front()[1];q
.pop();if(rooms
[x
][y
]==0){rooms
[i
][j
] = step
;found
= true;break;}for(k
= 0; k
< 4; ++k
){nx
= x
+ dir
[k
][0];ny
= y
+ dir
[k
][1];if(nx
>=0 && nx
<m
&& ny
>=0 && ny
<n
&& !visited
[nx
][ny
] && rooms
[nx
][ny
] != -1){q
.push({nx
,ny
});visited
[nx
][ny
] = true;}}}if(found
)break;step
++;}}}}
};
2.2 從門開始逆向BFS
- 對所有的門同時進行BFS,逆向考慮,每個位置最多訪問一次
class Solution {
public:void wallsAndGates(vector
<vector
<int>>& rooms
) {if(rooms
.size()==0 || rooms
[0].size()==0) return;int INF
= INT_MAX
, i
, j
, k
,step
= 0,size
,x
,y
,nx
,ny
;int m
= rooms
.size(), n
= rooms
[0].size();vector
<vector
<int>> dir
= {{1,0},{0,1},{0,-1},{-1,0}};vector
<vector
<bool>> visited(m
, vector
<bool>(n
,false)); queue
<vector
<int>> q
;for(i
= 0; i
< m
; ++i
){for(j
= 0; j
< n
; ++j
){if(rooms
[i
][j
]==0){visited
[i
][j
] = true;q
.push({i
,j
});}}}while(!q
.empty()){ size
= q
.size();while(size
--){x
= q
.front()[0];y
= q
.front()[1];q
.pop();if(rooms
[x
][y
]==INF
){rooms
[x
][y
] = step
;}for(k
= 0; k
< 4; ++k
){nx
= x
+ dir
[k
][0];ny
= y
+ dir
[k
][1];if(nx
>=0 && nx
<m
&& ny
>=0 && ny
<n
&& !visited
[nx
][ny
] && rooms
[nx
][ny
] != -1){q
.push({nx
,ny
});visited
[nx
][ny
] = true;}}}step
++;}}
};
124 ms 18.8 MB
長按或掃碼關注我的公眾號,一起加油、一起學習進步!
總結
以上是生活随笔為你收集整理的LeetCode 286. 墙与门(BFS)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。