多源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;
    }
};
相关推荐
许小燚12 分钟前
线性表——双向链表
数据结构·链表
董董灿是个攻城狮37 分钟前
5分钟搞懂什么是窗口注意力?
算法
Dann Hiroaki43 分钟前
笔记分享: 哈尔滨工业大学CS31002编译原理——02. 语法分析
笔记·算法
qqxhb2 小时前
零基础数据结构与算法——第四章:基础算法-排序(上)
java·数据结构·算法·冒泡·插入·选择
晚云与城3 小时前
【数据结构】顺序表和链表
数据结构·链表
FirstFrost --sy4 小时前
数据结构之二叉树
c语言·数据结构·c++·算法·链表·深度优先·广度优先
森焱森4 小时前
垂起固定翼无人机介绍
c语言·单片机·算法·架构·无人机
搂鱼1145145 小时前
(倍增)洛谷 P1613 跑路/P4155 国旗计划
算法
Yingye Zhu(HPXXZYY)5 小时前
Codeforces 2021 C Those Who Are With Us
数据结构·c++·算法
liulilittle6 小时前
LinkedList 链表数据结构实现 (OPENPPP2)
开发语言·数据结构·c++·链表