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;
    }
相关推荐
Joe_Wang51 小时前
[图论]拓扑排序
数据结构·c++·算法·leetcode·图论·拓扑排序
梭七y2 小时前
【力扣hot100题】(033)合并K个升序链表
算法·leetcode·链表
月亮被咬碎成星星2 小时前
LeetCode[383]赎金信
算法·leetcode
trust Tomorrow4 小时前
每日一题-力扣-2278. 字母在字符串中的百分比 0331
算法·leetcode
梭七y9 小时前
【力扣hot100题】(022)反转链表
算法·leetcode·链表
LuckyLay15 小时前
LeetCode算法题(Go语言实现)_22
算法·leetcode·golang
jndingxin18 小时前
OpenCV 图形API(5)API参考:数学运算用于执行图像或矩阵加法操作的函数add()
opencv·webpack·矩阵
Stardep19 小时前
算法学习11——滑动窗口——最大连续1的个数
数据结构·c++·学习·算法·leetcode·动态规划·牛客网
AQin101220 小时前
【Leetcode·中等】如何初始化(583.两个字符串的删除操作·Delete Operation for Two Strings)
java·算法·leetcode·动态规划
hnsqls20 小时前
LeetCode 精简75 题
算法·leetcode·职场和发展