问题描述
给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。
两个相邻元素间的距离为 1 。
示例 1:
输入:
0 0 0
0 1 0
0 0 0
输出:
0 0 0
0 1 0
0 0 0
示例 2:
输入:
0 0 0
0 1 0
1 1 1
输出:
0 0 0
0 1 0
1 2 1
注意:
给定矩阵的元素个数不超过 10000。
给定矩阵中至少有一个元素是 0。
矩阵中的元素只在四个方向上相邻: 上、下、左、右。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/01-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
- 1、遍历矩阵,找出所有的0,这些0到0的距离就是0
- 2、遍历矩阵,对所有不是0的元素,按照距离1、2、3、4…依次进行计算,并设置一个base来表示每次计算的距离
- 3、使用一个计数器,计算有多少元素已经找到到最近的0,当计数器=矩阵元素之和时就终止循环
代码实现
class Solution {
public int[][] updateMatrix(int[][] matrix) {
int lineNum = matrix.length;
int colNum = matrix[0].length;
int setCellNum = 0;
int base = 0;
while (setCellNum < lineNum * colNum) {
for (int lineNo = 0; lineNo < lineNum; lineNo++) {
for (int colNo = 0; colNo < colNum; colNo++) {
if (matrix[lineNo][colNo] == 0 && base == 0) {
setCellNum++;
continue;
}
if (matrix[lineNo][colNo] == base) {
boolean findDistanceEqualBase = false;
for (int lineNoPlus = -base; lineNoPlus <= base; lineNoPlus++) {
if (lineNo + lineNoPlus < 0 || lineNo + lineNoPlus >= lineNum){
continue;
}
int actualLineNo = lineNo + lineNoPlus;
int colNoPlusAbs = base - Math.abs(lineNoPlus);
if (colNoPlusAbs == 0) {
int actualColNo = colNo + colNoPlusAbs;
if (actualColNo < colNum && matrix[actualLineNo][actualColNo] == 0) {
matrix[lineNo][colNo] = base;
setCellNum ++;
findDistanceEqualBase = true;
break;
}
} else {
int actualColNoUpper = colNo + colNoPlusAbs;
int actualColNoLower = colNo - colNoPlusAbs;
boolean colNoUpperCellSatisfied = actualColNoUpper < colNum && matrix[actualLineNo][actualColNoUpper] == 0;
boolean colNoLowerCellSatisfied = actualColNoLower >= 0 && matrix[actualLineNo][actualColNoLower] == 0;
if (colNoUpperCellSatisfied || colNoLowerCellSatisfied) {
matrix[lineNo][colNo] = base;
setCellNum ++;
findDistanceEqualBase = true;
break;
}
}
}
if (!findDistanceEqualBase){
matrix[lineNo][colNo] = base + 1;
}
}
}
}
base++;
}
return matrix;
}
}