题目描述
题目来源于leetcod:https://leetcode-cn.com/explore/learn/card/queue-stack/220/conclusion/892/
给定一个由 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。
矩阵中的元素只在四个方向上相邻: 上、下、左、右。
分析
此题和墙与门问题几乎一模一样,从0开始进行广度优先遍历,将0四周是1的值置为当前层数+1,但不同的是,由于矩阵是0、1,而1本身又是一个解答会得到的值,所以,为了防止死循环,我们将坐标为1的值改为-1。
更详细的解答可以参考墙与门问题:https://blog.youkuaiyun.com/admite/article/details/107289151
代码
class Solution {
private List<int[]> action = Arrays.asList(
new int[] {0,1},
new int[] {0,-1},
new int[] {1,0},
new int[] {-1,0}
);
public int[][] updateMatrix(int[][] matrix) {
if(matrix == null || matrix.length==0) {
return matrix;
}
int l_length = matrix.length;
int v_length = matrix[0].length;
LinkedList<int[]> list = new LinkedList<>();
for(int i=0;i<l_length;i++) {
for(int j=0;j<v_length;j++) {
if(matrix[i][j]==0) {
list.add(new int[] {i,j});
}
if(matrix[i][j]==1) {
matrix[i][j] = -1;
}
}
}
while(!list.isEmpty()) {
int[] x = list.poll();
int a = x[0];
int b = x[1];
for(int[] y:action) {
int m = a + y[0];
int n = b + y[1];
if(m<0 || m>l_length-1 || n<0 || n>v_length-1 || matrix[m][n]!=-1) {
continue;
}
matrix[m][n] = matrix[a][b] + 1;
list.add(new int[] {m,n});
}
}
return matrix;
}
}