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

542. 01 矩阵

给定一个由 0 和 1 组成的矩阵 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;
    }
};
相关推荐
旖旎夜光1 天前
LeetCode 493: 翻转对 (归并排序) —— 题解
c++·笔记·学习·算法·leetcode·排序算法
木井巳1 天前
【动态规划: 子序列问题】最长递增子序列的个数
java·算法·leetcode·动态规划·推荐算法
Navigator_Z1 天前
LeetCode //C - 1326. Minimum Number of Taps to Open to Water a Garden
c语言·算法·leetcode
Rain的Java大神之路2 天前
LeetCode 45 跳跃游戏 II:大厂面试官最爱追问的贪心题,我把骨头给你拆干净了
java·后端·leetcode
Regulus-Moon3 天前
人工智能数学基础:矩阵特征分解与压缩实战
人工智能·线性代数·矩阵
让我们一起加油好吗3 天前
【算法刷题】LeetCode 力扣 Hot 100 刷题记录
数据结构·c++·算法·leetcode·面试·笔试
Rain的Java大神之路3 天前
LeetCode 42「接雨水」:面试官百出不厌的题,一文讲透从暴力到双指针 O(1)
java·后端·leetcode
Navigator_Z5 天前
LeetCode //C - 1320. Minimum Distance to Type a Word Using Two Fingers
c语言·算法·leetcode
wy_hhxx6 天前
[Leetcode] 滑动窗口
算法·leetcode·滑动窗口
AIgorithmGEEK6 天前
算法·哈希表|从“逐个比”到“按 key 算位置”
数据结构·c++·算法·leetcode·hash