Input:
[[0,0,0],
[0,1,0],
[1,1,1]]
Output:
[[0,0,0],
[0,1,0],
[1,2,1]]
Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.
思路:这个思路比较巧妙的是,把0全部收集起来,然后从0开始往1里面走,往里面走,都是步子+1;
class Solution {
public int[][] updateMatrix(int[][] mat) {
if(mat == null || mat.length == 0 || mat[0].length == 0) {
return mat;
}
int m = mat.length;
int n = mat[0].length;
Queue<int[]> queue = new LinkedList<>();
boolean[][] visited = new boolean[m][n];
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});
visited[i][j] = true;
}
}
}
int[][] dirs = {{0,1},{0,-1},{-1,0},{1,0}};
while(!queue.isEmpty()) {
int size = queue.size();
for(int i = 0; i < size; i++) {
int[] node = queue.poll();
int x = node[0];
int y = node[1];
for(int[] dir: dirs) {
int nx = x + dir[0];
int ny = y + dir[1];
if(0 <= nx && nx < m && 0 <= ny && ny < n
&& !visited[nx][ny] && mat[nx][ny] == 1) {
mat[nx][ny] = mat[x][y] + 1;
visited[nx][ny] = true;
queue.offer(new int[]{nx, ny});
}
}
}
}
return mat;
}
}