ID | Title | Difficulty | |
---|---|---|---|
Loading... |
286. Walls and Gates
Medium
LeetCode
Array, Breadth-First Search, Matrix
Problem
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 value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647. 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
Code
class Solution {
public void wallsAndGates(int[][] rooms) {
Queue<int[]> queue = new LinkedList<>();
for(int i = 0; i < rooms.length; i++){
for(int j = 0; j < rooms[0].length; j++){
if(rooms[i][j] == 0){
queue.add(new int[]{i, j});
}
}
}
int[][] dirs = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
int curr = 0;
while(!queue.isEmpty()){
int size = queue.size();
for(int i = 0; i < size; i++){
int[] loc = queue.poll();
int row = loc[0];
int col = loc[1];
rooms[row][col] = Math.min(curr, rooms[row][col]);
for(int[] dir : dirs){
int x = row + dir[0];
int y = col + dir[1];
if(x < 0 || y < 0 || x >= rooms.length || y >= rooms[0].length) continue;
if(rooms[x][y] != Integer.MAX_VALUE) continue;
queue.offer(new int[]{x, y});
}
}
curr++;
}
}
}
class Solution:
def helper(self, i: int, j: int, step: int, rooms: List[List[int]]) -> None:
if i < 0 or i >= len(rooms) or j < 0 or j >= len(rooms[0]):
return
if rooms[i][j] < step:
return
rooms[i][j] = step
self.helper(i + 1, j, step + 1, rooms)
self.helper(i - 1, j, step + 1, rooms)
self.helper(i, j + 1, step + 1, rooms)
self.helper(i, j - 1, step + 1, rooms)
def wallsAndGates(self, rooms: List[List[int]]) -> None:
"""
Do not return anything, modify rooms in-place instead.
"""
for i in range(len(rooms)):
for j in range(len(rooms[0])):
if rooms[i][j] == 0:
self.helper(i, j, 0, rooms)
class Solution:
def wallsAndGates(self, rooms: List[List[int]]) -> None:
"""
Do not return anything, modify rooms in-place instead.
"""
queue = deque()
for i in range(len(rooms)):
for j in range(len(rooms[0])):
if rooms[i][j] == 0:
queue.append((i, j))
step = 0
moves = [[1, 0], [-1, 0], [0, 1], [0, -1]]
while len(queue):
size = len(queue)
for i in range(size):
node = queue.popleft()
for move_index in range(4):
move = moves[move_index]
next_i = node[0] + move[0]
next_j = node[1] + move[1]
if next_i < 0 or next_i >= len(rooms) or next_j < 0 or next_j >= len(rooms[0]):
continue
if rooms[next_i][next_j] < step + 1:
continue
rooms[next_i][next_j] = step + 1
queue.append((next_i, next_j))
step += 1
按 <- 键看上一题!
285. Inorder Successor in BST
按 -> 键看下一题!
287. Find the Duplicate Number