多源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;
    }
};
相关推荐
幸幸子.22 分钟前
LeetCode 组合总数
c++·算法·leetcode
☆璇34 分钟前
【C++】哈希
c++·算法·哈希算法
Warren981 小时前
Java Record 类 — 简化不可变对象的写法
java·开发语言·jvm·分布式·算法·mybatis·dubbo
数据智能老司机2 小时前
图算法趣味学——桥和割点
数据结构·算法·云计算
菜就多练,以前是以前,现在是现在2 小时前
Codeforces Round 1042 (Div. 3)
c++·算法
John.Lewis3 小时前
数据结构初阶(11)排序的概念与运用
c语言·数据结构·排序算法
FPGA3 小时前
曼彻斯特编解码:数字世界的“摩斯密码”与FPGA高效实现
数据结构
数据智能老司机3 小时前
图算法趣味学——图遍历
数据结构·算法·云计算
范特西_4 小时前
交错字符串-二维dp
算法·动态规划
是阿建吖!4 小时前
【递归、搜索与回溯算法】穷举、暴搜、深搜、回溯、剪枝
算法·bfs·剪枝