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;
    }
相关推荐
乌萨奇也要立志学C++20 分钟前
【LeetCode】set和map相关算法题 前K个高频单词、随机链表的复制、两个数组的交集、环形链表
算法·leetcode·链表
设计师小聂!11 小时前
力扣热题100------136.只出现一次的数字
数据结构·算法·leetcode
崎岖Qiu12 小时前
leetcode643:子数组最大平均数 I(滑动窗口入门之定长滑动窗口)
java·算法·leetcode·力扣·双指针·滑动窗口
flashlight_hi13 小时前
LeetCode 分类刷题:2824. 统计和小于目标的下标对数目
javascript·数据结构·算法·leetcode
苹果薯条16 小时前
动手学习深度学习-相关数学知识
python·深度学习·机器学习·矩阵·numpy·反向传播·计算图
এ᭄画画的北北17 小时前
力扣-11.盛最多水的容器
算法·leetcode
冬夜戏雪17 小时前
java学习 73矩阵置零 54螺旋矩阵 148排序链表
数据结构·算法·矩阵
Dream it possible!18 小时前
LeetCode 面试经典 150_数组/字符串_O(1)时间插入、删除和获取随机元素(12_380_C++_中等)(哈希表)
c++·leetcode·面试·哈希表
快去睡觉~18 小时前
力扣137:只出现一次的数字Ⅱ
数据结构·算法·leetcode
云云32119 小时前
亚矩阵云手机:解锁 Shopee/Lazada 东南亚电商运营“通关密码
大数据·人工智能·物联网·线性代数·智能手机·矩阵