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;
    }
相关推荐
历程里程碑2 小时前
滑动窗口---- 无重复字符的最长子串
java·数据结构·c++·python·算法·leetcode·django
TracyCoder1233 小时前
LeetCode Hot100(18/100)——160. 相交链表
算法·leetcode
放荡不羁的野指针4 小时前
leetcode150题-滑动窗口
数据结构·算法·leetcode
TracyCoder1235 小时前
LeetCode Hot100(13/100)——238. 除了自身以外数组的乘积
算法·leetcode
Anastasiozzzz5 小时前
LeetCode Hot100 215. 数组中的第K个最大元素
数据结构·算法·leetcode
让我上个超影吧5 小时前
【力扣76】最小覆盖子串
算法·leetcode·职场和发展
求真求知的糖葫芦6 小时前
耦合传输线分析学习笔记(八)对称耦合微带线S参数矩阵推导与应用(上)
笔记·学习·矩阵·射频工程
求梦8207 小时前
【力扣hot100题】合并两个有序链表(22)
算法·leetcode·链表
踩坑记录7 小时前
leetcode hot100 21.合并两个有序链表 链表 easy
leetcode
IT_Octopus7 小时前
力扣热题100 20. 有效的括号
算法·leetcode