LeetCode 542. 01 矩阵

542. 01 矩阵

笔记 x*col+y这里卡了很久

class Solution {
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
        row=matrix.size(), col=matrix[0].size();
        vector<vector<int>> res(row);
        for(int i=0;i<row;i++) res[i].resize(col);
        fill(visited, visited+10005, false);
        for(int i=0;i<row;i++){
            for(int j=0;j<col;j++){
                if(matrix[i][j]==0) res[i][j]=0;
                else res[i][j]=get_value(i, j, matrix, res);
            }
        }
        return res;
    }
private:
    int row, col;
    bool visited[10005];
    vector<vector<int> > v = {{1,0},{-1,0},{0,1},{0,-1}};
    int get_value(int x, int y, vector<vector<int>>& matrix, vector<vector<int>>& res){
        queue<vector<int>> q;
        q.push({x, y});
        int step = 0;
        while(!q.empty()){
            int size = q.size();
            while(size){
                vector<int> t = q.front();
                x=t[0];y=t[1];
                if(matrix[x][y]==0){
                    visited[x*col+y]=true;
                    return step;
                }
                if(visited[x*col+y]==true){
                    return step+res[x][y];
                }
                q.pop();
                for(int i=0;i<4;i++){
                    int nx = t[0]+v[i][0], ny=t[1]+v[i][1];
                    if(nx<row && ny <col && nx>=0 && ny>=0){
                        q.push({nx, ny});
                    }
                }
                size--;
            }
            step++;
        }
        return 0;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值