01 Matrix
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.
BFS
Time Complexity
O(m*n)
Space Complexity
O(N)
思路
Iterate the matrix, put all 0 into queue and take all 1 into Integer.MAX_VALUE. This is the a common way to represent visited in matrix which can save space.
Do BFS, if the four surrounded direction's value is smaller or equal to the current matrix value means it has been visited so just continue, else change the value to the current matrix value + 1.
代码
public int[][] updateMatrix(int[][] matrix) {
//corner case
if(matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return null;
Queue<int[]> queue = new LinkedList<int[]>();
int rows = matrix.length, cols = matrix[0].length;
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
if(matrix[i][j] == 0){
queue.offer(new int[]{i, j});
}else if(matrix[i][j] == 1){
matrix[i][j] = Integer.MAX_VALUE;
}
}
}
int[][] directions = new int[][]{{-1,0},{1,0},{0,1},{0,-1}};
while(!queue.isEmpty()){
int size = queue.size();
for(int i = 0; i < size; i++){
int[] cur = queue.poll();
for(int[] dir : directions){
int x = cur[0] + dir[0];
int y = cur[1] + dir[1];
if(x < 0 || x >= rows || y < 0 || y >= cols || matrix[x][y] <= matrix[cur[0]][cur[1]]) continue;
matrix[x][y] = matrix[cur[0]][cur[1]] + 1;
queue.offer(new int[]{x,y});
}
}
}
return matrix;
}