多源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;
    }
};
相关推荐
imuliuliang1 分钟前
算法中的随机化思想及其复杂度收益评估的技术7
算法
不能跑的代码不是好代码21 分钟前
二叉树从基础概念到LeetCode实战
算法·leetcode
凯瑟琳.奥古斯特44 分钟前
二分查找解力扣1011最优运载能力
开发语言·c++·算法·leetcode·职场和发展
学计算机的计算基1 小时前
二叉树算法下篇:递归核心技巧与高频面试题详解
java·笔记·算法
水龙吟啸1 小时前
华为2026.6.24机考选择题+编程题【速刷敲黑板】
人工智能·深度学习·算法·机器学习·华为
Eloudy1 小时前
全文 - Evolution Strategies as a Scalable Alternative to Reinforcement Learning
人工智能·算法
Yang_jie_031 小时前
笔记:数据结构(链表)
数据结构·笔记·链表
net3m332 小时前
可以加大adc滑动滤波的间隔时间,比如定时每20ms采集一次滤波输入,且用滑动窗口均值滤波
算法
卷福同学8 小时前
不用服务器,不用配环境,我10分钟上线了一个AI Agent
人工智能·后端·算法
问君能有几多愁~10 小时前
C++ 数据结构复习笔记
数据结构·c++·笔记