1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
private int[][] DIRECTIONS = new int[][] { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };

public void wallsAndGates(int[][] rooms) {
Deque<int[]> posQ = new ArrayDeque<>();
for (int row = 0; row < rooms.length; row++) {
for (int col = 0; col < rooms[0].length; col++) {
if (rooms[row][col] == 0) {
posQ.offerLast(new int[] { row, col });
}
}
}
int steps = 0;
while (!posQ.isEmpty()) {
int size = posQ.size();
for (int i = 0; i < size; i++) {
int[] currPos = posQ.pollFirst();
for (int[] direction : DIRECTIONS) {
int newRow = currPos[0] + direction[0];
int newCol = currPos[1] + direction[1];
if (!isOutOfBound(rooms, newRow, newCol) && rooms[newRow][newCol] == Integer.MAX_VALUE) {
rooms[newRow][newCol] = steps + 1;
posQ.offerLast(new int[] { newRow, newCol });
}
}
}
steps += 1;
}
}

private boolean isOutOfBound(int[][] rooms, int row, int col) {
return row < 0 || row >= rooms.length || col < 0 || col >= rooms[0].length;
}
}

就是BFS. 和01 matrix那道题一模一样.

时间复杂度: O(m * n)
空间复杂度: O(max(m, n))