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.
2.输入输出样例子
Example 1:
Input:
[[0,0,0],
[0,1,0],
[0,0,0]]
Output:
[[0,0,0],
[0,1,0],
[0,0,0]]
Example 2:
Input:
[[0,0,0],
[0,1,0],
[1,1,1]]
Output:
[[0,0,0],
[0,1,0],
[1,2,1]]
Note:
- The number of elements of the given matrix will not exceed 10,000.
- There are at least one 0 in the given matrix.
- The cells are adjacent in only four directions: up, down, left and right.
2.解法
- 题解:给定的二维矩阵(仅包含0和1),输出各点到0最近的距离(两个坐标点之间的距离单位1)。
class Solution {
// 定义四个点的方向
int [] deltaX=new int[]{0,0,1,-1};
int [] deltaY=new int[]{1,-1,0,0};
public int[][] updateMatrix(int[][] matrix) {
// 思路:非常典型的DFS问题,当一个点不是0时,需要搜索四周使当前距离最小,同理,采用DFS对四周继续遍历
int m=matrix.length;
int n=matrix[0].length;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(matrix[i][j]!=0){
DFS(matrix,i,j);
}
}
}
return matrix;
}
public void DFS(int [][] matrix,int x,int y){
int min=Integer.MAX_VALUE;
// 先取四周最小的值
for(int i=0;i<deltaX.length;i++){
int nextX=deltaX[i]+x;
int nextY=deltaY[i]+y;
if(nextX>=0&&nextX<matrix.length&&nextY>=0&&nextY<matrix[0].length){
// 取四周最小的值
min=Math.min(min,matrix[nextX][nextY]+1);
}
}
// 判断最小值是否跟当前判断点相同
if(min!=matrix[x][y]){
matrix[x][y]=min;
// 更换为最小值后,同理往四周遍历
for(int i=0;i<deltaX.length;i++){
int nextX=deltaX[i]+x;
int nextY=deltaY[i]+y;
if(nextX>=0&&nextX<matrix.length&&nextY>=0&&nextY<matrix[0].length){
DFS(matrix,nextX,nextY);
}
}
}
}
}