多源 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;
    }
};
相关推荐
Y1nhl1 小时前
力扣_链表_python版本
开发语言·python·算法·leetcode·链表·职场和发展
闻缺陷则喜何志丹1 小时前
【BFS】 P10864 [HBCPC2024] Genshin Impact Startup Forbidden II|普及+
c++·算法·宽度优先·洛谷
Swift社区3 小时前
Swift 解 LeetCode 320:一行单词有多少种缩写可能?用回溯找全解
开发语言·leetcode·swift
YuTaoShao13 小时前
【LeetCode 热题 100】48. 旋转图像——转置+水平翻转
java·算法·leetcode·职场和发展
百年孤独_21 小时前
LeetCode 算法题解:链表与二叉树相关问题 打打卡
算法·leetcode·链表
我爱C编程21 小时前
基于拓扑结构检测的LDPC稀疏校验矩阵高阶环检测算法matlab仿真
算法·matlab·矩阵·ldpc·环检测
算法_小学生1 天前
LeetCode 75. 颜色分类(荷兰国旗问题)
算法·leetcode·职场和发展
算法_小学生1 天前
LeetCode 287. 寻找重复数(不修改数组 + O(1) 空间)
数据结构·算法·leetcode
岁忧1 天前
(LeetCode 每日一题) 1865. 找出和为指定值的下标对 (哈希表)
java·c++·算法·leetcode·go·散列表
alphaTao1 天前
LeetCode 每日一题 2025/6/30-2025/7/6
算法·leetcode·职场和发展