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;
    }
相关推荐
我爱豆子1 小时前
Leetcode Hot 100刷题记录 -Day19(回文链表)
java·算法·leetcode·链表
程序猿练习生1 小时前
C++速通LeetCode中等第18题-删除链表的倒数第N个结点(最简单含注释)
c++·leetcode·链表
m0_571957582 小时前
Java | Leetcode Java题解之第424题替换后的最长重复字符
java·leetcode·题解
我要学编程(ಥ_ಥ)8 小时前
双指针算法专题(2)
数据结构·算法·leetcode
我要学编程(ಥ_ಥ)10 小时前
滑动窗口算法专题(1)
java·数据结构·算法·leetcode
LluckyYH11 小时前
代码随想录Day 46|动态规划完结,leetcode题目:647. 回文子串、516.最长回文子序列
数据结构·人工智能·算法·leetcode·动态规划
huanxiangcoco11 小时前
73. 矩阵置零
python·leetcode·矩阵
源代码:趴菜11 小时前
LeetCode118:杨辉三角
算法·leetcode·动态规划
luluvx11 小时前
LeetCode[中等] 74.搜索二维矩阵
算法·leetcode·矩阵
sjsjs1113 小时前
【数据结构-扫描线】力扣57. 插入区间
数据结构·算法·leetcode