给定一个由 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
思路:
输入数组为 a
创建一个二维数组result储存每个元素到0的位置 准备返回
创建队储存已经确定长度的位置
遍历一遍输入 如果是0就在result对应位置写0 如果不是就写成int最大值
此时队列中已经存在的元素是 长度为0的所有值
然后只需要把每一个确定的元素向外扩散 如果扩散到的位置大小是大于 自身大小+1
那么将 自身大小+1 赋值给扩散位置 同时将扩散位置加入队列中
public int[][] updateMatrix(int[][] matrix) {
int[][] result = new int[matrix.length][matrix[0].length];
Queue<int[]> q = new LinkedList<>();
for (int i = 0; i < matrix.length; i++) {
int[] a = matrix[i];
for (int j = 0; j < a.length; j++) {
if (matrix[i][j] == 0) {
q.add(new int[]{i, j});
result[i][j] = 0;
} else {
result[i][j] = Integer.MAX_VALUE;
}
}
}
while (!q.isEmpty()) {
int[] index = q.poll();
int i = index[0];
int j = index[1];
int length = result[i][j];
if (i != 0) {
// 如果i!=0就有上面
int top = result[i - 1][j];
if (top > length + 1) {
result[i - 1][j] = length + 1;
q.add(new int[]{i - 1, j});
}
}
if (i != matrix.length - 1) {
// 如果i不等于最下面一排就有下面
int below = result[i + 1][j];
if (below > length + 1) {
result[i+1][j] = length + 1;
q.add(new int[]{i + 1, j});
}
}
if (j != 0) {
// 如果j不等于0就有左边
int left = result[i][j - 1];
if (left > length + 1) {
result[i][j - 1] = length + 1;
q.add(new int[]{i, j - 1});
}
}
if (j != matrix[0].length - 1) {
// 有右边
int right = result[i][j + 1];
if (right > length + 1) {
result[i][j + 1] = length + 1;
q.add(new int[]{i, j+1});
}
}
}
return result;
}