多源 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;
    }
};
相关推荐
琢磨先生David8 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
超级大福宝8 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll8 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐8 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶8 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode
im_AMBER8 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
样例过了就是过了8 天前
LeetCode热题100 环形链表 II
数据结构·算法·leetcode·链表
tyb3333339 天前
leetcode:吃苹果和队列
算法·leetcode·职场和发展
踩坑记录9 天前
leetcode hot100 74. 搜索二维矩阵 二分查找 medium
leetcode
TracyCoder1239 天前
LeetCode Hot100(60/100)——55. 跳跃游戏
算法·leetcode