多源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;
    }
};
相关推荐
hansang_IR1 小时前
【题解】P5364 [SNOI2017] 礼物
c++·线性代数·算法
Tisfy1 小时前
LeetCode 3871.统计范围内的逗号 II:每次算一个逗号
数学·算法·leetcode·题解
小O的算法实验室1 小时前
IEEE TEVC,基于K-means与DQN辅助元启发式算法的多目标两栖无人艇调度模型
算法·kmeans·启发式算法
zcmodeltech1 小时前
冷链物流沙盘模型控制系统设计——基于STM32与Modbus RTU的冷藏车、冷库全流程动态展示方案
数据结构·stm32·单片机·嵌入式硬件·物联网·能源
mmmmath_31 小时前
LeetCode.350.两个数组的交集II
算法
Ivanqhz1 小时前
图是“拓扑 + 类型 + 形状“的世界
算法·决策树·机器学习·php·集成学习
find1star1 小时前
LeetCode 54:螺旋矩阵——用四个边界模拟矩阵收缩
java·算法·leetcode·边缘计算·学习方法
z_mazin2 小时前
逆向一种私有二进制序列化格式:从零到字节级解析器
网络·python·网络协议·算法·rpc
luj_17682 小时前
罚球线右移破防新策略
c语言·开发语言·网络·经验分享·算法
vivo互联网技术2 小时前
SmartPhotoCrafter: 先思考后修图,统一理解-生成的图像优化新范式
人工智能·算法·计算机视觉