给定一个由 0 和 1 组成的矩阵 mat ,请输出一个大小相同的矩阵,其中每一个格子是 mat 中对应位置元素到最近的 0 的距离。
两个相邻元素间的距离为 1 。
示例 1:
输入:mat = [[0,0,0],[0,1,0],[0,0,0]]
输出:[[0,0,0],[0,1,0],[0,0,0]]
示例 2:
输入:mat = [[0,0,0],[0,1,0],[1,1,1]]
输出:[[0,0,0],[0,1,0],[1,2,1]]
提示:
m == mat.length
n == mat[i].length
1 <= m, n <= 104
1 <= m * n <= 104
mat[i][j] is either 0 or 1.
mat 中至少有一个 0
class Solution {
static int[] dirs = new int[]{-1, 0, 1, 0, -1};
public int[][] updateMatrix(int[][] mat) {
int n = mat.length, m = mat[0].length;
int[][] res = new int[n][m];
for (int i = 0; i < n; ++i) Arrays.fill(res[i], -1);
Deque<int[]> q = new LinkedList<>();
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
if (mat[i][j] == 0) {
q.addLast(new int[]{i, j});
res[i][j] = 0;
}
while (!q.isEmpty()) {
int[] t = q.pollFirst();
for (int i = 0; i < 4; ++i) {
int a = t[0] + dirs[i], b = t[1] + dirs[i + 1];
if (a < 0 || a >= n || b < 0 || b >= m) continue;
if (res[a][b] != -1) continue;
res[a][b] = res[t[0]][t[1]] + 1;
q.addLast(new int[]{a, b});
}
}
return res;
}
}