Untitled

mail@pastecode.io avatar
unknown
c_cpp
2 months ago
1.1 kB
3
Indexable
Never
class Solution {
public:

    bool isValid(int i, int j, int m, int n){
        if(i==m || j==n || i<0 || j<0)
            return false;
        return true;    
    }

    vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
        
        int m=mat.size();
        int n=mat[0].size();
        vector<vector<int>> res(m, vector<int>(n,-1));
        vector<vector<int>> dir{{0,1}, {0,-1}, {1,0}, {-1,0}};

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

        while(!q.empty()){
            auto cur = q.front();
           

            for(auto &z : dir){
                 int x=cur.first+z[0];
                 int y=cur.second+z[1];
                 if(isValid(x,y,m,n) && res[x][y]==-1){
                    q.push({x,y});
                    res[x][y]=res[cur.first][cur.second]+1;
                 }
            }
           
        }

        return res;
    }
};
Leave a Comment