多源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;
    }
};
相关推荐
惊讶的猫3 小时前
字符串- 字符串转换整数 (atoi)
数据结构·算法
@小码农3 小时前
2025年北京海淀区中小学生信息学竞赛第一赛段试题(附答案)
人工智能·python·算法·蓝桥杯
2301_795167203 小时前
玩转Rust高级应用 如何让让运算符支持自定义类型,通过运算符重载的方式是针对自定义类型吗?
开发语言·后端·算法·安全·rust
laocooon5238578863 小时前
C语言 有关指针,都要学哪些内容
c语言·数据结构·算法
多多*4 小时前
牛客周赛 Round 114 Java题解
算法
他们叫我一代大侠4 小时前
Leetcode :模拟足球赛小组各种比分的出线状况
算法·leetcode·职场和发展
Nebula_g4 小时前
C语言应用实例:硕鼠游戏,田忌赛马,搬桌子,活动选择(贪心算法)
c语言·开发语言·学习·算法·游戏·贪心算法·初学者
liu****5 小时前
11.Linux进程信号(三)
linux·运维·服务器·数据结构·1024程序员节
AI科技星5 小时前
张祥前统一场论动量公式P=m(C-V)误解解答
开发语言·数据结构·人工智能·经验分享·python·线性代数·算法
海琴烟Sunshine5 小时前
leetcode 345. 反转字符串中的元音字母 python
python·算法·leetcode