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;
    }
相关推荐
Nazarick2 小时前
力扣LeetCode热题75题(1)
java·算法·leetcode·力扣
16月6日-晴2 小时前
斐波那契数列题解
算法·leetcode
一水鉴天3 小时前
立二必三:矩阵、三空间与三推理 20261205(元宝)
人工智能·矩阵·架构
Tisfy5 小时前
LeetCode 3561.移除相邻字符:栈(相邻相消)
算法·leetcode·字符串·题解·栈·相邻相消
Navigator_Z9 小时前
LeetCode //C - 1332. Remove Palindromic Subsequences
c语言·算法·leetcode
Nazarick10 小时前
力扣LeetCode热题(3)
java·算法·leetcode·贪心算法
Rain的Java大神之路10 小时前
LeetCode 46 全排列:从「及格答案」到让面试官眼前一亮的三种写法
后端·leetcode·面试
Shaoshing12 小时前
LeetCode100 152.乘积最大子数组
数据结构·算法·leetcode
吞下星星的少年·-·12 小时前
力扣 162. 寻找峰值(枚举,二分查找)
算法·leetcode·枚举·二分
Shaoshing1 天前
LeetCode 921.使括号括号有效的最少添加
java·算法·leetcode·职场和发展