多源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;
    }
};
相关推荐
VL——MOESR40 分钟前
【LuoguP1967】货车运输【生成树】【倍增】
c++·算法·题解·倍增·生成树
手写码匠42 分钟前
华为云Flexus+DeepSeek征文|Agent 记忆系统实战:用 DeepSeek-R1/V3 + Dify 会话变量打造跨会话长期记忆
人工智能·深度学习·算法·aigc
Olafur_zbj1 小时前
【AI】CUDA编程中的维度
人工智能·算法
疯狂打码的少年2 小时前
【数据结构】栈:定义、顺序栈与链式栈
数据结构·笔记
坚持编程的菜鸟2 小时前
模拟实现memcpy
c语言·算法·模拟实现my_memcpy
wabs6662 小时前
关于图论【最短路径之Bellman_ford 算法|卡码网94.城市间货物运输的思考】
数据结构·算法·图论·卡码网·bellman_ford·求最短路径
MrZhao4002 小时前
On-Policy Distillation(OPD):为什么大模型后训练要在学生自己的轨迹上蒸馏?
算法
今日无bug2 小时前
JS 数据类型 + 内存分配:从 8 种类型到栈堆模型
javascript·数据结构
朱峥嵘(朱髯)2 小时前
数据库如何根据全表 NDV 估算子集的 NDV
数据库·算法
jjjava2.02 小时前
牛客算法题(第四期)
算法