多源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;
    }
};
相关推荐
?abc!2 小时前
(数组)448. 找到所有数组中消失的数字
算法
淡海水2 小时前
05-03-源码-Boehm GC分配与碎片管理
开发语言·算法·unity·c#·游戏引擎·gc
青少儿编程课堂2 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C/C++考级:任意进制互转与大数多进制加法解析
c++·python·算法·bfs·信息学竞赛
多弗朗皮卡丘3 小时前
C++ 哈希(下)
c++·算法·哈希算法
敲代码的苦133 小时前
头歌数据结构-排序的实现及其应用
数据结构
aichitang20243 小时前
Meta Muse Spark Open:816B 巨型开放权重多模态 Agent 模型架构、部署实战与社区首测全解
大数据·人工智能·python·算法·ai·架构·spark
Coder-magician3 小时前
图论总结篇
算法·图论
有同事要进步3 小时前
Leecode第68题:x的平方根
java·数据结构·算法
吹什么轩3 小时前
linux系统复习:进程优先级与O(1)调度
java·linux·算法
开开心心就好4 小时前
安卓PDF处理工具,免费无广告零弹窗
android·服务器·开发语言·算法·pdf·ocr