Leecode 542. 01 矩阵 (多源BFS搜索)

 

正向思路是对每个1进行BFS搜索,这样时间复杂度较高,采用逆向思路,从多源0开始搜索,找到1。然后跟新距离

const int dx[] = {0, 1, -1, 0};
const int dy[] = {1, 0, 0, -1};

class Solution {
public:

    // 朴素算法,从每个1出发做一次BFS搜索
    // 多源优化,从0开始向1作多源最短路 
    vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
        int n = matrix.size(), m = matrix[0].size();

        vector<vector<int>> res(n, vector<int>(m, -1));
        queue<pair<int, int>> q;
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                if(matrix[i][j] == 0){
                    res[i][j] = 0;
                    q.push({i, j});
                }
            }
        }

        while(!q.empty()){
            auto [x, y] = q.front();
            q.pop();
            for(int i = 0; i < 4; i++){
                int a = x + dx[i];
                int b = y + dy[i];
                if(a >= 0 && a < n && b >= 0 && b < m && res[a][b] == -1){
                    res[a][b] = res[x][y] + 1;
                    q.push({a, b});
                }
            }
        }
        return res;
    }
};

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值