You are given a m x n 2D grid initialized with these three possible values.
-1
- A wall or an obstacle.0
- A gate.INF
- Infinity means an empty room. We use the value231 - 1 = 2147483647
to representINF
as you may assume that the distance to a gate is less than2147483647
.
Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF
.
Example:
Given the 2D grid:
INF -1 0 INF
INF INF INF -1
INF -1 INF -1
0 -1 INF INF
After running your function, the 2D grid should be:
3 -1 0 1
2 2 1 -1
1 -1 2 -1
0 -1 3 4 這個題目是用BFS來解決, 最naive approach就是掃每個點,然後針對每個點用BFS一旦找到0, 代替點的值. 時間複雜度為 O((m*n)^2);
我們還是用BFS的思路, 但是我們先把2D arr 掃一遍, 然後把是0的位置都append進入queue裡面, 因為是BFS, 所以每一層最靠近0的位置都會被替換, 並且標記為visited, 然後一直BFS到最後即可.
時間複雜度降為O(m*n) 1. Constraints
1) empty or len(rooms[0]) == 0, edge case
2) size of the rooms < inf
3) 每個元素的值為0, -1, inf 2. Ideas BFS T: O(m*n) S: O(m*n) 1) edge case,empty or len(rooms[0]) == 0 => return
2) scan 2D arr, 將值為0 的append進入queue裡面
3) BFS, 如果是not visited過得, 並且 != 0 or -1, 更改值為dis + 1, 另外append進入queue, add進入visited 3. Code
class Solution:
def wallAndGates(self, rooms):
if not rooms or len(rooms[0]) == 0: return
queue, lr, lc, visited, dirs = collections.deque(), len(rooms), len(rooms[0]), set(), [(1, 0), (-1, 0), (0, 1), (0, -1)]
for i in range(lr):
for j in range(lc):
if rooms[i][j] == 0:
queue.append((i, j, 0))
visited.add((i, j)) while queue:
pr, pc, dis = queue.popleft()
for d1, d2 in dirs:
nr, nc = pr + d1, pc + d2
if 0<= nr < lr and 0<= nc < lc and (nr, nc) not in visited and rooms[nr][nc] != -1:
rooms[nr][nc] = dis + 1
queue.append((nr,nc, dis + 1))
visited.add((nr, nc))
4. Test cases
1) edge case
2)
INF -1 0 INF
INF INF INF -1
INF -1 INF -1
0 -1 INF INF
After running function, the 2D grid should be:
3 -1 0 1
2 2 1 -1
1 -1 2 -1
0 -1 3 4