|
15 | 15 | - Worst time: O(mn), where entre rooms[][] are gates. It takes O(mn) to complete the iteration. Other gates be skipped by `if (rooms[x][y] <= dist) return;` |
16 | 16 |
|
17 | 17 | #### BFS |
18 | | -- TODO? why BFS better? |
| 18 | +- Exact same concept. Init with `Queue<int[]> queue = new LinkedList<int[]>()` |
19 | 19 |
|
20 | 20 | ``` |
21 | 21 | /* |
@@ -89,6 +89,53 @@ private boolean validate(int[][] rooms) { |
89 | 89 |
|
90 | 90 | } |
91 | 91 |
|
| 92 | + |
| 93 | +// BFS: |
| 94 | + |
| 95 | +class Solution { |
| 96 | + int[] dx = {1, -1, 0, 0}; |
| 97 | + int[] dy = {0, 0, 1, -1}; |
| 98 | + |
| 99 | + public void wallsAndGates(int[][] rooms) { |
| 100 | + if (validate(rooms)) return; |
| 101 | + int m = rooms.length, n = rooms[0].length; |
| 102 | + Queue<int[]> queue = new LinkedList<>(); |
| 103 | + |
| 104 | + // Initi with 0 |
| 105 | + for (int i = 0; i < m; i++) { |
| 106 | + for (int j = 0; j < n; j++) { |
| 107 | + if (rooms[i][j] == 0) {// test all 0's with for loop |
| 108 | + queue.offer(new int[] {i, j}); |
| 109 | + } |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + // Process queue |
| 114 | + while (!queue.isEmpty()) { |
| 115 | + int[] point = queue.poll(); |
| 116 | + bfsHelper(rooms, queue, point[0], point[1]); |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + // Process with queue, and skip of value depth > existing depth. |
| 121 | + private void bfsHelper(int[][] rooms, Queue<int[]> queue, int x, int y) { |
| 122 | + for (int i = 0; i < dx.length; i++) { |
| 123 | + int mX = x + dx[i], mY = y + dy[i]; |
| 124 | + if (validateCoordinate(rooms, mX, mY) || rooms[x][y] + 1 > rooms[mX][mY]) continue; |
| 125 | + rooms[mX][mY] = rooms[x][y] + 1; |
| 126 | + queue.offer(new int[] {mX, mY}); |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + private boolean validateCoordinate(int[][] rooms, int x, int y) { |
| 131 | + return x < 0 || x >= rooms.length || y < 0 || y >= rooms[0].length || rooms[x][y] == -1 || rooms[x][y] == 0; |
| 132 | + } |
| 133 | + |
| 134 | + private boolean validate(int[][] rooms) { |
| 135 | + return rooms == null || rooms.length == 0 || rooms[0] == null || rooms[0].length == 0; |
| 136 | + } |
| 137 | + |
| 138 | +} |
92 | 139 | /* |
93 | 140 | Form empty room: it can reach different gate, but each shortest length will be determined by the 4 directions. |
94 | 141 | Option1. DFS on INF, mark visited, summerize results of 4 directions. it's hard to resue: we do not know the direction in cached result dist[i][j] |
|
0 commit comments