Skip to content

Commit 6468380

Browse files
authored
Update Walls and Gates.java
1 parent 702ac46 commit 6468380

File tree

1 file changed

+48
-1
lines changed

1 file changed

+48
-1
lines changed

Java/Walls and Gates.java

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
- 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;`
1616

1717
#### BFS
18-
- TODO? why BFS better?
18+
- Exact same concept. Init with `Queue<int[]> queue = new LinkedList<int[]>()`
1919

2020
```
2121
/*
@@ -89,6 +89,53 @@ private boolean validate(int[][] rooms) {
8989

9090
}
9191

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+
}
92139
/*
93140
Form empty room: it can reach different gate, but each shortest length will be determined by the 4 directions.
94141
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

Comments
 (0)