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;
    }
相关推荐
小辉同志9 小时前
215. 数组中的第K个最大元素
数据结构·算法·leetcode··快速选择
memcpy010 小时前
LeetCode 2615. 等值距离和【相同元素分组+前缀和;考虑距离和的增量】中等
算法·leetcode·职场和发展
alphaTao10 小时前
LeetCode 每日一题 2026/4/20-2026/4/26
算法·leetcode·职场和发展
风一样的航哥12 小时前
LeetCode 2615 等值距离和:前缀和优化O(n)解法深度解析
数据结构·算法·leetcode
旖-旎13 小时前
深搜(二叉树的所有路径)(6)
c++·算法·leetcode·深度优先·递归
khalil102015 小时前
代码随想录算法训练营Day-34动态规划03 | 01背包问题 二维、01背包问题 一维、416. 分割等和子集
数据结构·c++·算法·leetcode·动态规划·背包问题·01背包
圣保罗的大教堂16 小时前
leetcode 3761. 镜像对之间最小绝对距离 中等
leetcode
6Hzlia16 小时前
【Hot 100 刷题计划】 LeetCode 108. 将有序数组转换为二叉搜索树 | C++ 分治法详解
c++·算法·leetcode
菜鸟丁小真18 小时前
LeetCode hot100 -131.分割回文串
数据结构·算法·leetcode·知识点总结
Cathy Bryant18 小时前
微分几何:度规(度量)metric
笔记·线性代数·矩阵·高等数学·物理