下图中就展示了我们方法:
class Solution {
public int[][] updateMatrix(int[][] mat) {
int m = mat.length, n = mat[0].length;
int[][] dist = new int[m][n];
boolean[][] used = new boolean[m][n];
Queue<int[]> queue = new LinkedList<>();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (mat[i][j] == 0) {
queue.offer(new int[]{i, j});
used[i][j] = true;
}
}
}
int[] xMove = new int[]{-1, 1, 0, 0};
int[] yMove = new int[]{0, 0, -1, 1};
while (!queue.isEmpty()) {
int[] curLoc = queue.poll();
int curX = curLoc[0], curY = curLoc[1];
for (int i = 0; i < 4; ++i) {
int xNew = curX + xMove[i];
int yNew = curY + yMove[i];
if (xNew >= 0 && xNew < m && yNew >= 0 && yNew < n && !used[xNew][yNew]) {
queue.offer(new int[]{xNew, yNew});
dist[xNew][yNew] = dist[curX][curY] + 1;
used[xNew][yNew] = true;
}
}
}
return dist;
}
}