多源BFS - 01矩阵

LCR 107. 01 矩阵

到最近的0的距离,对每一个非0的位置进行搜索,找到最短的距离即可,但如果对每一个非0的点都进行一次搜索的话,肯定是会超时的。这里可以考虑,将所有0点想象成一个0点(超级0)。然后找到所有1点到超级0的距离即可。

复制代码
class Solution {
public:
    int dx[4] = {0,0,1,-1};
    int dy[4] = {1,-1,0,0};

    vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
        int n = mat.size(), m = mat[0].size();
        vector<vector<int>> dist(n, vector<int>(m, 0));
        vector<vector<int>> st(n, vector<int>(m));
        queue<pair<int,int>> q;
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                if (mat[i][j] == 0)
                {
                    st[i][j] = 1;
                    q.push({i, j});
                }
            }
        }

        while (!q.empty()) 
        {
            auto t = q.front();
            q.pop();
            int x = t.first;
            int y = t.second;
            for (int i = 0; i < 4; i++)
            {
                int xx = x + dx[i];
                int yy = y + dy[i];
                if (xx >= 0 && xx < n && yy >= 0 && yy < m && !st[xx][yy])
                {
                    st[xx][yy] = 1;
                    dist[xx][yy] = dist[x][y] + 1;
                    q.push({xx, yy});
                }
            }
            
        }
        return dist;
    }
};
相关推荐
kobesdu几秒前
开源3D激光SLAM算法的异同点、优劣势与适配场景总结
算法·3d·机器人·ros
ZC跨境爬虫3 分钟前
3D 地球卫星轨道可视化平台开发 Day13(卫星可视化交互优化+丝滑悬停聚焦)
前端·算法·3d·json·交互
水木流年追梦6 分钟前
CodeTop Top 100 热门题目(按题型分类)
算法·leetcode
Tisfy13 分钟前
LeetCode 1722.执行交换操作后的最小汉明距离:连通图
算法·leetcode·dfs·题解·深度优先搜索·连通图
不知名的老吴20 分钟前
案例教学:最长递增子序列问题
数据结构·算法·动态规划
样例过了就是过了21 分钟前
LeetCode热题100 杨辉三角
c++·算法·leetcode·动态规划
念越28 分钟前
算法每日一题 Day05|双指针解决盛最多水的容器问题
算法·力扣
_小草鱼_30 分钟前
【数据结构】栈和队列
数据结构·数组··队列
eggrall30 分钟前
Leetcode 最大连续 1 的个数 III(medium)
算法·leetcode·职场和发展
啊我不会诶31 分钟前
Educational Codeforces Round 120 (Rated for Div. 2) vp补题
c++·算法