|
| 1 | +/**************************************************************************************************** |
| 2 | +286. Walls and Gates |
| 3 | +
|
| 4 | +Difficulty: Medium |
| 5 | +
|
| 6 | +You are given a m x n 2D grid initialized with these three possible values. |
| 7 | +-1 - A wall or an obstacle. |
| 8 | +0 - A gate. |
| 9 | +INF - Infinity means an empty room. |
| 10 | +(We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647.) |
| 11 | +
|
| 12 | +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. |
| 13 | +
|
| 14 | +Example: |
| 15 | +Given the 2D grid: |
| 16 | +INF -1 0 INF |
| 17 | +INF INF INF -1 |
| 18 | +INF -1 INF -1 |
| 19 | + 0 -1 INF INF |
| 20 | +
|
| 21 | +After running your function, the 2D grid should be: |
| 22 | + 3 -1 0 1 |
| 23 | + 2 2 1 -1 |
| 24 | + 1 -1 2 -1 |
| 25 | + 0 -1 3 4 |
| 26 | +****************************************************************************************************/ |
| 27 | + |
| 28 | + |
| 29 | +class Solution { |
| 30 | + public void wallsAndGates(int[][] rooms) { |
| 31 | + //记录四个方向,向 上下左右(i +- 1, j +- 1)方向前进。 |
| 32 | + final int[][] DIRS = new int[][] {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; |
| 33 | + // if (rooms == null || rooms.length == 0 || rooms[0].length == 0) { |
| 34 | + // return rooms; |
| 35 | + // } |
| 36 | + |
| 37 | + Queue<int[]> queue = new LinkedList<>(); |
| 38 | + //遍历一遍二维数组,将为 0 (即是 gate 的格子)放入队列 queue 中。 |
| 39 | + for (int i = 0; i < rooms.length; i++) { |
| 40 | + for (int j = 0; j < rooms[0].length; j++) { |
| 41 | + if (rooms[i][j] == 0) { |
| 42 | + queue.offer(new int[] {i, j}); |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + while (!queue.isEmpty()) { |
| 48 | + int[] cur = queue.poll(); |
| 49 | + int i = cur[0]; |
| 50 | + int j = cur[1]; |
| 51 | + //从当前点向 上下左右 前进一格。如果前进到达的新的这一格为 INF,则 + 1。并且放入队列 queue 中,未来继续遍历它的四个方向。 |
| 52 | + for (int[] pairs : DIRS) { |
| 53 | + int x = i + pairs[0]; |
| 54 | + int y = j + pairs[1]; |
| 55 | + if (x < 0 || x >= rooms.length || y < 0 || y >= rooms[0].length || rooms[x][y] != Integer.MAX_VALUE) { |
| 56 | + continue; |
| 57 | + } |
| 58 | + rooms[x][y] = rooms[i][j] + 1; |
| 59 | + queue.add(new int[] {x, y}); |
| 60 | + } |
| 61 | + } |
| 62 | + //return rooms; |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | + |
0 commit comments