多源 BFS_多源最短路(十八)542. 01 矩阵 中等 超级源点思想

542. 01 矩阵

给定一个由 01 组成的矩阵 mat ,请输出一个大小相同的矩阵,其中每一个格子是 mat 中对应位置元素到最近的 0 的距离。

两个相邻元素间的距离为 1

示例 1:

复制代码
输入:mat = [[0,0,0],[0,1,0],[0,0,0]]
输出:[[0,0,0],[0,1,0],[0,0,0]]

示例 2:

复制代码
输入:mat = [[0,0,0],[0,1,0],[1,1,1]]
输出:[[0,0,0],[0,1,0],[1,2,1]]

提示:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 104
  • 1 <= m * n <= 104
  • mat[i][j] is either 0 or 1.
  • mat 中至少有一个 0

正难则反

很难从1出发去找每一个最近的0,这样就只能使用单源最短路径bfs求解,最终导致复杂度过高。所以可以将所有的0作为一个超级源点,把所有的起点加入队列,剩下的就都是1,然后利用这个队列进行bfs操作,每访问一个结点,就更新它的step步数值,并放入book标记数组里。

cpp 复制代码
class Solution {
public:
    int m, n;
    typedef pair<int, int> PII;
    int dx[4] = {0, 0, 1, -1};
    int dy[4] = {1, -1, 0, 0};
    vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
        m = mat.size(), n = mat[0].size();
        vector<vector<bool>> book(m, vector(n, false));
        queue<PII> q;
        
    1、将所有的 0 作为一个超级源点放入队列中
        for(int i = 0; i < m; i++)
        {
            for(int j = 0; j < n; j++)
            {
                if(mat[i][j] == 0)
                {
                    q.push({i, j});
                    book[i][j] = true;
                }
            }
        }

    2、利用bfs操作更新所有值为1的结点
        int step = 0;
        while(q.size())
        {
            
            step++;
            int sz = q.size();
            while(sz--)
            {
                auto [a, b] = q.front();
                q.pop();
                for(int k = 0; k < 4; k++)
                {
                    int x = a + dx[k];
                    int y = b + dy[k];
                    if(x >= 0 && y >= 0 && x < m && y < n && !book[x][y])
                    {
                        // if(mat[x][y] == 1) 0放入队列了,mat中只有1,无需判断直接处理即可
                        mat[x][y] = step;
                        book[x][y] = true;
                        q.push({x, y});
                    }
                }
            }
        }
        return mat;
    }
};
相关推荐
YoungHong19924 小时前
面试经典150题[072]:从前序与中序遍历序列构造二叉树(LeetCode 105)
leetcode·面试·职场和发展
im_AMBER5 小时前
Leetcode 78 识别数组中的最大异常值 | 镜像对之间最小绝对距离
笔记·学习·算法·leetcode
LYFlied6 小时前
【每日算法】LeetCode 25. K 个一组翻转链表
算法·leetcode·链表
LYFlied9 小时前
【每日算法】LeetCode 19. 删除链表的倒数第 N 个结点
算法·leetcode·链表
努力学算法的蒟蒻10 小时前
day35(12.16)——leetcode面试经典150
算法·leetcode·面试
LYFlied11 小时前
【每日算法】LeetCode 234. 回文链表详解
算法·leetcode·链表
刃神太酷啦11 小时前
C++ list 容器全解析:从构造到模拟实现的深度探索----《Hello C++ Wrold!》(16)--(C/C++)
java·c语言·c++·qt·算法·leetcode·list
承渊政道11 小时前
一文彻底搞清楚链表算法实战大揭秘和双向链表实现
c语言·数据结构·算法·leetcode·链表·visual studio
玉树临风ives13 小时前
atcoder ABC436 题解
c++·算法·leetcode·atcoder·信息学奥赛
圣保罗的大教堂13 小时前
leetcode 2110. 股票平滑下跌阶段的数目 中等
leetcode