286. Walls and Gates
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
.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.
1 public class Solution { 2 public void wallsAndGates(int[][] rooms) { 3 if (rooms == null || rooms.length == 0) return; 4 int m = rooms.length, n = rooms[0].length; 5 6 for (int i = 0; i < m; i++) { 7 for (int j = 0; j < n; j++) { 8 if (rooms[i][j] == 0) { 9 helper(i, j, 0, rooms); 10 } 11 } 12 } 13 } 14 15 private void helper(int row, int col, int distance, int[][] rooms) { 16 int rows = rooms.length, cols = rooms[0].length; 18 if (row < 0 || row >= rows || col < 0 || col >= cols || rooms[row][col] == -1) return; 20 if (distance > rooms[row][col]) return; 22 if (distance < rooms[row][col]) { 23 rooms[row][col] = distance; 24 } 26 helper(row - 1, col, distance + 1, rooms); 27 helper(row + 1, col, distance + 1, rooms); 28 helper(row, col - 1, distance + 1, rooms); 29 helper(row, col + 1, distance + 1, rooms); 30 } 31 }
BFS
对于bfs,因为我们是把所有的0点在最开始的时候加入到了queue里面,所以,当其中一个0点访问到一个空点的时候,那么我们一定可以说那是最短距离。所以,时间复杂度上,bfs比dfs好很多。
1 public class Solution { 2 public void wallsAndGates(int[][] rooms) { 3 Queue<int[]> queue = new LinkedList<int[]>(); 4 int rows = rooms.length; 5 if (rows == 0) { 6 return; 7 } 8 int cols = rooms[0].length; 9 10 // 找出所有BFS的起始点 11 for (int i = 0; i < rows; i++) { 12 for (int j = 0; j < cols; j++) { 13 if (rooms[i][j] == 0) { 14 queue.offer(new int[]{i, j}); 15 } 16 } 17 } 18 19 // 定义下一步的位置 20 int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; 21 22 // 开始BFS 23 while (!queue.isEmpty()) { 24 int[] top = queue.poll(); 25 for (int k = 0; k < dirs.length; k++) { 26 int x = top[0] + dirs[k][0]; 27 int y = top[1] + dirs[k][1]; 28 if (x >= 0 && x < rows && y >= 0 && y < cols && rooms[x][y] == Integer.MAX_VALUE) { 29 rooms[x][y] = rooms[top[0]][top[1]] + 1; 30 queue.add(new int[]{x, y}); 31 } 32 } 33 } 34 } 35 }
From:
http://buttercola.blogspot.com/2015/09/leetcode-walls-and-gates.html
https://segmentfault.com/a/1190000004184488