[LeetCode] 286. Walls and Gates

墙与门。题意是给一个二维矩阵,里面的-1代表墙,0代表门,INF代表一个空的房间。请改写所有的INF,表明每个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

这一题还是flood fill类的题目,既然是问最短距离,所以我这个题目就用BFS做了。

时间O(mn)

空间O(mn)

Java实现

 1 class Solution {
 2     public void wallsAndGates(int[][] rooms) {
 3         // corner case
 4         if (rooms == null || rooms.length == 0) {
 5             return;
 6         }
 7 
 8         // normal case
 9         Queue<int[]> queue = new LinkedList<>();
10         for (int i = 0; i < rooms.length; i++) {
11             for (int j = 0; j < rooms[0].length; j++) {
12                 if (rooms[i][j] == 0) {
13                     queue.add(new int[] { i, j });
14                 }
15             }
16         }
17         while (!queue.isEmpty()) {
18             int[] cur = queue.poll();
19             int row = cur[0], col = cur[1];
20             if (row > 0 && rooms[row - 1][col] == Integer.MAX_VALUE) {
21                 rooms[row - 1][col] = rooms[row][col] + 1;
22                 queue.offer(new int[] { row - 1, col });
23             }
24             if (row < rooms.length - 1 && rooms[row + 1][col] == Integer.MAX_VALUE) {
25                 rooms[row + 1][col] = rooms[row][col] + 1;
26                 queue.offer(new int[] { row + 1, col });
27             }
28             if (col > 0 && rooms[row][col - 1] == Integer.MAX_VALUE) {
29                 rooms[row][col - 1] = rooms[row][col] + 1;
30                 queue.offer(new int[] { row, col - 1 });
31             }
32             if (col < rooms[0].length - 1 && rooms[row][col + 1] == Integer.MAX_VALUE) {
33                 rooms[row][col + 1] = rooms[row][col] + 1;
34                 queue.offer(new int[] { row, col + 1 });
35             }
36         }
37     }
38 }

 

上一篇:【转载】 Bill Gates和Elon Musk推荐,人工智能必读的三本书 -《终极算法》,《超级智能》和《终极发明》


下一篇:HTTPS 安全传输原理