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;
    }
相关推荐
凌波粒24 分钟前
LeetCode--344.反转字符串(字符串/双指针法)
算法·leetcode·职场和发展
啊哦呃咦唔鱼33 分钟前
LeetCode hot100-543 二叉树的直径
算法·leetcode·职场和发展
样例过了就是过了2 小时前
LeetCode热题100 爬楼梯
c++·算法·leetcode·动态规划
ThisIsMirror2 小时前
leetcode 452 Arrays.sort()排序整数溢出、Integer.compare(a[1], b[1])成功的问题
算法·leetcode
x_xbx3 小时前
LeetCode:438. 找到字符串中所有字母异位词
算法·leetcode·职场和发展
派大星~课堂4 小时前
【力扣-94.二叉树的中序遍历】Python笔记
笔记·python·leetcode
AI成长日志4 小时前
【笔面试算法学习专栏】堆与优先队列实战:力扣hot100之215.数组中的第K个最大元素、347.前K个高频元素
学习·算法·leetcode
6Hzlia4 小时前
【Hot 100 刷题计划】 LeetCode 45. 跳跃游戏 II | C++ 贪心算法最优解题解
c++·leetcode·游戏
北顾笙9804 小时前
day18-数据结构力扣
数据结构·算法·leetcode
阿Y加油吧5 小时前
LeetCode 中等难度 | 回溯法进阶题解:单词搜索 & 分割回文串
算法·leetcode·职场和发展