一、题目描述
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.
二、题解
暴力的思路很简单:初始化一个dists数组记录0与1的距离
- 当
<i,j>位置为0时,dists数组自然记录该位置为0 - 当
<i,j>位置为1时,从头开始遍历,在遍历的过程中只要位置<k,l>是0,计算与<i,j>位置的距离dist_01,在这个过程中取最小的dist_01
(1)暴力破解
public class Main {
public static int[][] updateMatrix(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
int max=Integer.MAX_VALUE;
int[][] dists = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
dists[i][j]=max;
if(matrix[i][j]==0)
dists[i][j]=0;
else if(matrix[i][j]==1) {
for (int k = 0; k < rows; k++)
for (int l = 0; l < cols; l++)
if(matrix[k][l]==0) {
int dist_01 = Math.abs(i-k)+Math.abs(j-l);
dists[i][j]=Math.min(dists[i][j], dist_01);
}
}
}
}
return dists;
}
public static void main(String[] args) {
int[][] m = new int[][] {
{0,0,0},
{0,1,0},
{0,0,0}
};
updateMatrix(m);
}
}
复杂度分析
- 时间复杂度:
O((r⋅c)^2)),对于每个为 1 的点都需要遍历整个矩阵一次。 - 空间复杂度:
O(r⋅c),dists数组的开销