Walls and Gates

时间:2023-03-08 18:52:33
Walls and Gates
You are given a m x n 2D grid initialized with these three possible values.
  1. -1 - A wall or an obstacle.
  2. 0 - A gate.
  3. 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 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.
For 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

Understand the problem:
It is very classic backtracking problem. We can start from each gate (0 point), and searching for its neighbors. We can either use DFS or BFS solution.

 public class Solution {
public void wallsAndGates(int[][] rooms) {
if (rooms == null || rooms.length == ) return;
int m = rooms.length, n = rooms[].length; for (int i = ; i < m; i++) {
for (int j = ; j < n; j++) {
if (rooms[i][j] == ) {
helper(i, j, , rooms);
}
}
}
} private void helper(int row, int col, int distance, int[][] rooms) {
int rows = rooms.length, cols = rooms[].length;
if (row < || row >= rows || col < || col >= cols || rooms[row][col] == -) return;
if (distance > rooms[row][col]) return;
if (distance < rooms[row][col]) {
rooms[row][col] = distance;
}
helper(row - , col, distance + , rooms);
helper(row + , col, distance + , rooms);
helper(row, col - , distance + , rooms);
helper(row, col + , distance + , rooms);
}
}

BFS

对于bfs,因为我们是把所有的0点在最开始的时候加入到了queue里面,所以,当其中一个0点访问到一个空点的时候,那么我们一定可以说那是最短距离。所以,时间复杂度上,bfs比dfs好很多。

 public class Solution {
public void wallsAndGates(int[][] rooms) {
Queue<int[]> queue = new LinkedList<int[]>();
int rows = rooms.length;
if (rows == ) {
return;
}
int cols = rooms[].length; // 找出所有BFS的起始点
for (int i = ; i < rows; i++) {
for (int j = ; j < cols; j++) {
if (rooms[i][j] == ) {
queue.offer(new int[]{i, j});
}
}
} // 定义下一步的位置
int[][] dirs = {{-, }, {, }, {, -}, {, }}; // 开始BFS
while (!queue.isEmpty()) {
int[] top = queue.poll();
for (int k = ; k < dirs.length; k++) {
int x = top[] + dirs[k][];
int y = top[] + dirs[k][];
if (x >= && x < rows && y >= && y < cols && rooms[x][y] == Integer.MAX_VALUE) {
rooms[x][y] = rooms[top[]][top[]] + ;
queue.add(new int[]{x, y});
}
}
}
}
}

From:

http://buttercola.blogspot.com/2015/09/leetcode-walls-and-gates.html

https://segmentfault.com/a/1190000004184488