-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDistance of nearest cell having 1.cpp
48 lines (44 loc) · 1.28 KB
/
Distance of nearest cell having 1.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
Problem Link: https://practice.geeksforgeeks.org/problems/distance-of-nearest-cell-having-1-1587115620/1
*/
class Solution
{
public:
//Function to find distance of nearest 1 in the grid for each cell.
vector<vector<int>>nearest(vector<vector<int>>grid)
{
// BFS Code here
int n= grid.size();
int m= grid[0].size();
vector<vector<int>> vis(n, vector<int>(m, 0));
vector<vector<int>> dist(n, vector<int>(m, 0));
queue<pair<pair<int,int>,int>> q;
// {{r,c},dist} will be the pattern
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
if(grid[i][j]==1){
q.push({{i,j}, 0});
vis[i][j]=1;
}
}
}
while(!q.empty()){
int row= q.front().first.first;
int col= q.front().first.second;
int steps= q.front().second;
q.pop();
dist[row][col]= steps;
int delrow[]={-1,0,1,0};
int delcol[]={0,1,0,-1};
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 && !vis[nrow][ncol]){
q.push({{nrow,ncol}, steps+1});
vis[nrow][ncol]=1;
}
}
}
return dist;
}
};