多源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;
    }
};
相关推荐
郝学胜-神的一滴5 小时前
Effective STL 条款 07:指针容器销毁前先删除
开发语言·c++·vscode·leetcode·rpc·visual studio
CoderYanger5 小时前
A.每日一题:2243. 计算字符串的数字和
java·开发语言·程序人生·leetcode·面试·蓝桥杯·学习方法
青少儿编程课堂8 小时前
蓝桥杯真题解析:三维偏序的CDQ分治(全国青少年信息素养大赛与电子学会编程考级)
c++·python·算法·bfs·信息学竞赛
Navigator_Z8 小时前
LeetCode //C - 1323. Maximum 69 Number
c语言·算法·leetcode
geovindu8 小时前
python:Lasso
开发语言·后端·python·算法
AAA修煤气灶刘哥9 小时前
同一个模型,为什么还要专门练一遍怎么用工具?
人工智能·后端·算法
AAA修煤气灶刘哥10 小时前
两个 Agent 各自改得都对,合在一起为什么出错?
人工智能·后端·算法
电科_银尘11 小时前
【大模型算法与工程 34】QLoRA:量化底座上的低秩训练
人工智能·算法·机器学习
专注仿真11 小时前
智能体训练:模仿学习与 MCTS 算法详解与实战
算法·强化学习·仿真·afsim智能体·仿真训练
逐光沧海12 小时前
数据结构-链表习题(C++)
数据结构·c++·链表