-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGFG Distance of nearest cell having 1
66 lines (59 loc) · 1.44 KB
/
GFG Distance of nearest cell having 1
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class Solution
{
public:
//Function to find distance of nearest 1 in the grid for each cell.
vector<vector<int>>nearest(vector<vector<int>>grid)
{
queue<pair<int,int>> q;
int m=grid.size();
int n=grid[0].size();
vector<vector<int>> ans(m,vector<int>(n,0));
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(grid[i][j]==1)
{
q.push({i,j});
grid[i][j]=0;
}
else
{
ans[i][j]=-1;
//grid[i][j]=-1;
}
}
}
vector<int> dirx={0,1,0,-1};
vector<int> diry={1,0,-1,0};
while(!q.empty())
{
int size=q.size();
for(int s=0;s<size;s++)
{
int x=q.front().first;
int y=q.front().second;
q.pop();
for(int i=0;i<4;i++)
{
int nx=x+dirx[i];
int ny=y+diry[i];
if(isInvalid(nx,ny,m,n)) continue;
//cout<<nx<<" "<<ny<<endl;
if(ans[nx][ny]==-1)
{
ans[nx][ny]=ans[x][y]+1;
q.push({nx,ny});
}
}
}
}
return ans;
}
bool isInvalid(int i,int j,int m,int n )
{
if(i<0 || j<0 || i>=m || j>=n )
return true;
return false;
}
};