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;
    }
相关推荐
跨境海王哥2 小时前
Facebook矩阵引流:从防封机制拆解
线性代数·矩阵·facebook
西西弗Sisyphus3 小时前
线性代数 - 二阶矩阵的行列式、向量叉积(Cross product)的模长与平行四边形面积的关系
线性代数·矩阵·行列式
_fairyland4 小时前
数据结构 力扣 练习
数据结构·考研·算法·leetcode
橘颂TA4 小时前
【剑斩OFFER】算法的暴力美学——山脉数组的蜂顶索引
算法·leetcode·职场和发展·c/c++
博语小屋5 小时前
力扣11.盛水最多的容器(medium)
算法·leetcode·职场和发展
Swift社区5 小时前
LeetCode 423 - 从英文中重建数字
算法·leetcode·职场和发展
bbq粉刷匠6 小时前
力扣--两数之和(Java)
java·leetcode
树在风中摇曳6 小时前
LeetCode 1658 | 将 x 减到 0 的最小操作数(C语言滑动窗口解法)
c语言·算法·leetcode
.柒宇.7 小时前
力扣hoT100之找到字符串中所有字母异位词(java版)
java·数据结构·算法·leetcode
YoungHong19928 小时前
面试经典150题[063]:删除链表的倒数第 N 个结点(LeetCode 19)
leetcode·链表·面试