Skip to content

Commit

Permalink
Create DistanceofNearestCellHaving1.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kshitiz11101 authored May 23, 2024
1 parent 5e2f3b9 commit a1c7bf9
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions Graphs/DistanceofNearestCellHaving1.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
class Solution
{
public:
//Function to find distance of nearest 1 in the grid for each cell.
vector<vector<int>>nearest(vector<vector<int>>grid)
{
// Code here
int n=grid.size(),m=grid[0].size();
vector<vector<int>>ans(n,vector<int>(m,0));
vector<vector<int>>visited(n,vector<int>(m,0));
queue<pair<pair<int,int>,int>>q;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(grid[i][j]==1){
q.push({{i,j},0});
visited[i][j]=1;
}
else{
visited[i][j]=0;
}
}
}
int delrow[]={-1,0,+1,0};
int delcol[]={0,+1,0,-1};
while(!q.empty()){
int row=q.front().first.first;
int col=q.front().first.second;
int steps=q.front().second;
q.pop();
ans[row][col]=steps;
for(int i=0;i<4;i++){
int nrow=row+delrow[i];
int ncol=col+delcol[i];
if(nrow>=0 && nrow<n && ncol>=0 && ncol<m && visited[nrow][ncol]==0 ){
visited[nrow][ncol]=1;
q.push({{nrow,ncol},steps+1});
}
}
}
return ans;
}
};

0 comments on commit a1c7bf9

Please sign in to comment.