leetcode 542. 01 Matrix(01矩阵)


矩阵中只有0,1值,返回每个cell到最近的0的距离。

思路:

0元素到它自己的距离是0,

只需考虑1到最近的0是多少距离。

BFS.

先把元素1处的距离更新为无穷大。

0的位置装入queue。

从每个0出发,走上下左右4个方向,遇到0不需要处理,遇到1,距离为当前距离+1.

如果当前距离+1 比下一位置的距离小,

把下一位置的距离更新为当前距离+1,同时说明从下一位置出发的距离都需要更新,装入queue.

java 复制代码
    public int[][] updateMatrix(int[][] mat) {
        int rows = mat.length;
        int cols = mat[0].length;

        Queue<int[]> queue = new LinkedList<>();
        int max = rows * cols;

        //初始化,0处加入queue, 1处设为最大值
        for(int r = 0; r < rows; r++) {
            for(int c = 0; c < cols; c++) {
                if(mat[r][c] == 0) queue.offer(new int[]{r,c});
                else mat[r][c] = max;
            }
        }

        int[] direc = new int[]{-1,0,1,0,-1};

        while(!queue.isEmpty()) {
            int[] cur = queue.poll();
            for(int i = 0; i < 4; i++) {
                int nextR = cur[0] + direc[i];
                int nextC = cur[1] + direc[i+1];
                if(nextR >= 0 && nextR < rows && nextC >= 0 && nextC < cols && mat[cur[0]][cur[1]]+1 < mat[nextR][nextC]){
                    mat[nextR][nextC] = mat[cur[0]][cur[1]]+1;
                    queue.offer(new int[]{nextR, nextC});
                }
            }
        }
        return mat;
    }
相关推荐
西西弗Sisyphus1 小时前
线性代数 - 奇异值分解(SVD Singular Value Decomposition)- 奇异值在哪里
线性代数·矩阵·奇异值分解·线程方程组
吃着火锅x唱着歌4 小时前
LeetCode 2016.增量元素之间的最大差值
数据结构·算法·leetcode
郝学胜-神的一滴5 小时前
计算机图形中的法线矩阵:深入理解与应用
开发语言·程序人生·线性代数·算法·机器学习·矩阵·个人开发
元亓亓亓6 小时前
LeetCode热题100--46. 全排列--中等
算法·leetcode·职场和发展
墨染点香6 小时前
LeetCode 刷题【146. LRU 缓存】
leetcode·缓存·哈希算法
qk学算法6 小时前
力扣滑动窗口题目-76最小覆盖子串&&1234替换子串得到平衡字符串
数据结构·算法·leetcode
小欣加油6 小时前
leetcode 860 柠檬水找零
c++·算法·leetcode·职场和发展·贪心算法
还是码字踏实6 小时前
基础数据结构之数组的矩阵遍历:螺旋矩阵(LeetCode 54 中等题)
数据结构·leetcode·矩阵·螺旋矩阵
西西弗Sisyphus7 小时前
线性代数 - 奇异值分解(SVD Singular Value Decomposition)- 计算顺序 旋转→拉伸→旋转
线性代数·矩阵·奇异值分解·矩阵求逆
唯道行7 小时前
计算机图形学·9 几何学
人工智能·线性代数·计算机视觉·矩阵·几何学·计算机图形学