LeetCode 542. 01 Matrix
| 考点 | 难度 |
|---|---|
| Array | Medium |
题目
Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.
The distance between two cells sharing a common edge is 1.
思路
Initialize queue with ALL 0 cells, mark 1 cells as -1 (unvisited)
Multi-source BFS: For each cell processed, check its 4 neighbors. If a neighbor is unvisited (-1), set its distance = current cell distance + 1 and add it to the queue
答案
class Solution {
int[] DIR = new int[]{0, 1, 0, -1, 0};
public int[][] updateMatrix(int[][] mat) {
int m = mat.length, n = mat[0].length; // The distance of cells is up to (M+N)
Queue<int[]> q = new ArrayDeque<>();
for (int r = 0; r < m; ++r)
for (int c = 0; c < n; ++c)
if (mat[r][c] == 0) q.offer(new int[]{r, c});
else mat[r][c] = -1; // Marked as not processed yet!
while (!q.isEmpty()) {
int[] curr = q.poll();
int r = curr[0], c = curr[1];
for (int i = 0; i < 4; ++i) {
int nr = r + DIR[i], nc = c + DIR[i+1];
if (nr < 0 || nr == m || nc < 0 || nc == n || mat[nr][nc] != -1) continue;
mat[nr][nc] = mat[r][c] + 1;
q.offer(new int[]{nr, nc});
}
}
return mat;
}
}

1万+

被折叠的 条评论
为什么被折叠?



