LeetCode原题:
给定一个由 0 和 1 组成的矩阵 mat ,请输出一个大小相同的矩阵,其中每一个格子是 mat 中对应位置元素到最近的 0 的距离。
两个相邻元素间的距离为 1 。
输入:mat = [[0,0,0],[0,1,0],[1,1,1]] 输出:[[0,0,0],[0,1,0],[1,2,1]]
思路捏,题目要求我们找1相邻最近的零的距离,那反过来我们可以找零到一的距离
*我们使用队列来存储二维数组中零的下标,这样方便我们后面遍历寻找数组元素一
*我们把二维数组元素一的值变成-1,这样方便我们标记是否遍历过这个位置,遍历过我们就赋值回去
*创建一个代表方向的数组int[] directions,方便我们后面队列元素走四个方向
*后面就是遍历队列了
代码如下:
public class Solution {
public static void main(String[] args) {
int[][] mat={{0,0,0},
{0,1,0},
{1,1,1}};
int[][] array=updateMatrix(mat);
for(int i=0;i<array.length;i++){
for(int j=0;j<array[i].length;j++){
System.out.print(array[i][j]);
}
System.out.println(" ");
}
}
public static int[][] updateMatrix(int[][] mat){
//创建一个标记方向的数组
int[] directions={-1,0,1,0,-1};
//创建一个队列,存储数组0元素的点
Queue<int[]> queue=new LinkedList<>();
//遍历数组,把0存储进队列中,把1变成-1(代表没有遍历到的标记,遍历到在改回来1)
for(int i=0;i<mat.length;i++){
for(int j=0;j<mat[i].length;j++){
if(mat[i][j]==0){
queue.offer(new int[]{i,j});
}else{
mat[i][j]=-1;
}
}
}
//创建一个标记0到1的距离的标量
int step=1;
//取出零元素数组遍历
while(!queue.isEmpty()){
//队列的长度
int size=queue.size();
//依次取出队列中0元素四个方向遍历
for(int i=0;i<size;i++){
//取出队列元素
int[] node=queue.poll();
//往四个方向走
for(int j=0;j<directions.length-1;j++){
//行左边
int x=node[0]+directions[j];
//纵坐标
int y=node[1]+directions[j+1];
//设置边界条件
if(x<0||x>=mat.length||y<0||y>=mat[0].length||mat[x][y]>=0){
//下标没有越界和遍历到不是-1的时候,继续
continue;
}
//找到-1的时候,赋值为1;
mat[x][y]=step;
//x,y坐标重新入队,这样可以一直遍历
queue.offer(new int[]{x,y});
}
}
//距离加加
step++;
}
return mat;
}
}
结果如下: