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;
    }
相关推荐
莫等闲-7 小时前
leetcode42. 接雨水 leetcode84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
浅念-7 小时前
LeetCode 记忆化搜索 刷题总结
数据结构·算法·leetcode·职场和发展·深度优先·dfs
菜菜的顾清寒7 小时前
力扣HOT100(44)对称二叉树
数据结构·算法·leetcode
吃好睡好便好7 小时前
矩阵的左乘和右乘
人工智能·学习·线性代数·算法·matlab·矩阵
学计算机的计算基8 小时前
LeetCode刷题笔记:数组专题四连击(LC53/56/189/41)
笔记·leetcode·排序算法
x_xbx8 小时前
LeetCode:543. 二叉树的直径
算法·leetcode·职场和发展
罗超驿9 小时前
11.LeetCode 1004. 最大连续1的个数 III | 滑动窗口解法详解(Java)
java·算法·leetcode
东方佑9 小时前
从量子矩阵力学到神经网络计算:一种跨学科的数学统一性探索
神经网络·线性代数·矩阵
吃好睡好便好9 小时前
矩阵的左除和右除
人工智能·学习·线性代数·算法·矩阵
小羊在睡觉18 小时前
力扣84. 柱状图中最大的矩形
后端·算法·leetcode·golang·go