LeetCode 542. 01 矩阵(Java)

542. 01 矩阵

给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。
两个相邻元素间的距离为 1 。

示例 1:
输入:
0 0 0
0 1 0
0 0 0
输出:
0 0 0
0 1 0
0 0 0

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/01-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
    public int[][] updateMatrix(int[][] matrix) {
        int len1=matrix.length;
        if(len1==0)
        {
            return new int[0][0];
        }
        int len2=matrix[0].length;
        //使用一个队列来存储访问过的坐标
        Queue<int[]> queue=new LinkedList<>();
        for(int i=0;i<len1;i++)
        {
            for(int j=0;j<len2;j++)
            {
                //如果该元素为0,则加入队列中
                if(matrix[i][j]==0)
                {
                    queue.add(new int[]{i,j});
                }
                else//否则将该坐标的值设为一个不可能达到的数
                {
                    matrix[i][j]=Integer.MAX_VALUE;
                }
            }
        }
        //四个方向
        int[][] dire={{0,1},{0,-1},{1,0},{-1,0}};
        while(queue.size()!=0)
        {
            int[] temp=queue.poll();
            for(int a=0;a<4;a++)
            {
                int x=temp[0]+dire[a][0];
                int y=temp[1]+dire[a][1];
                //如果新坐标的值大于当前坐标的值加一,那么说明从本结点出发距离更近,则修改新坐标的值,并将新坐标加入队列中
                if(x>=0&&y>=0&&x<len1&&y<len2&&matrix[x][y]>matrix[temp[0]][temp[1]]+1)
                {
                    matrix[x][y]=matrix[temp[0]][temp[1]]+1;
                    queue.add(new int[]{x,y});
                }
            }
        }
        return matrix;
    }
}
发布了88 篇原创文章 · 获赞 0 · 访问量 2160

猜你喜欢

转载自blog.csdn.net/nuts_and_bolts/article/details/105082224