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
35
36
37
38
39
class Solution {
private int[][] directions = new int[][] { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };

public int maxDistance(int[][] grid) {
boolean[][] cellDistance = new boolean[grid.length][grid[0].length];
Deque<int[]> cellQ = new ArrayDeque<>();
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1) {
cellDistance[i][j] = true;
cellQ.offer(new int[] { i, j });
}
}
}
if (cellQ.isEmpty() || cellQ.size() == grid.length * grid[0].length) {
return -1;
}
int distance = 0;
while (!cellQ.isEmpty()) {
for (int i = cellQ.size(); i > 0; i--) {
int[] currPos = cellQ.poll();
for (int[] direction : directions) {
int newRow = currPos[0] + direction[0];
int newCol = currPos[1] + direction[1];
if (!isOutOfBound(grid, newRow, newCol) && !cellDistance[newRow][newCol]) {
cellDistance[newRow][newCol] = true;
cellQ.offer(new int[] { newRow, newCol });
}
}
}
distance += 1;
}
return distance - 1;
}

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

BFS就完事儿了.

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