多源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;
    }
};
相关推荐
SHARK_pssm21 分钟前
【数据结构——树与堆】
c语言·数据结构·经验分享·笔记
bIo7lyA8v41 分钟前
算法可视化对教学与调试效率的影响分析的技术8
算法
hunterkkk(c++)1 小时前
优先队列启发式最短路径快速算法(优化SPFA)-HEAP_SPFA算法
算法
SiliconGazer1 小时前
第15届国赛满分代码解析(下)—— 运动轨迹算法、按键交互与完整状态机
算法·状态机·stc15f2k60s2·浮点运算·蓝桥杯国赛·运动轨迹、·向量分解
Navigator_Z1 小时前
LeetCode //C - 1096. Brace Expansion II
c语言·算法·leetcode
luj_17681 小时前
FreeDOS vs MS-DOS PC-DOS 对比解析
服务器·c语言·开发语言·经验分享·算法
RH2312111 小时前
2026.6.10 数据结构 二叉树
数据结构
笨笨没好名字1 小时前
Leetcode刷题python版第一周
python·算法·leetcode
Cthy_hy1 小时前
斯特林数:组合划分的递归经典,一二两类全解
python·算法·斯特林数
不忘不弃2 小时前
计算pi的近似值
算法