Leetcode 286 Walls and Gates
It’s smart to enqueue all the 0s at the same time, rather than empty the queue of one 0 and enqueue the next. So whenever an empty room is reached, it must be from the closest gate.
private static final int EMPTY = Integer.MAX_VALUE;
private static final int GATE = 0;
private static final List<int[]> DIRECTIONS = Arrays.asList(
new int[] { 1, 0},
new int[] {-1, 0},
new int[] { 0, 1},
new int[] { 0, -1}
);
public void wallsAndGates(int[][] rooms) {
int m = rooms.length;
if (m == 0) return;
int n = rooms[0].length;
Queue<int[]> q = new LinkedList<>();
for (int row = 0; row < m; row++) {
for (int col = 0; col < n; col++) {
if (rooms[row][col] == GATE) {
q.add(new int[] { row, col });
}
}
}
while (!q.isEmpty()) {
int[] point = q.poll();
int row = point[0];
int col = point[1];
for (int[] direction : DIRECTIONS) {
int r = row + direction[0];
int c = col + direction[1];
if (r < 0 || c < 0 || r >= m || c >= n || rooms[r][c] != EMPTY) {
continue;
}
rooms[r][c] = rooms[row][col] + 1;
q.add(new int[] { r, c });
}
}
}
For example:
step 1:
INF, -1, 0, INF
INF, INF, INF, -1
INF, -1, INF, -1
0, -1, INF, INF
Queue : (0,2), (3,0)
step 2:
INF, -1, 0, 1
INF, INF, 1, -1
1, -1, INF, -1
0, -1, INF, INF
Queue : (0,3),(1,2), (2,0)
step 3:
INF, -1, 0, 1
2, 2, 1, -1
1, -1, 2, -1
0, -1, INF, INF
Queue : (1,0),(1,1),(2,2)
step 4:
3, -1, 0, 1
2, 2, 1, -1
1, -1, 2, -1
0, -1, 3, INF
Queue : (0, 0) , (3,2)
step 4:
3, -1, 0, 1
2, 2, 1, -1
1, -1, 2, -1
0, -1, 3, 4
Queue : (3,3)
step 5:
Queue is null