Skip to content

Commit cc80eb2

Browse files
authored
Create 28 October Distance of nearest cell having 1 (#919)
2 parents 8697e7e + eb69a8a commit cc80eb2

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
class Solution {
2+
public:
3+
vector<vector<int>>nearest(vector<vector<int>>grid)
4+
{
5+
int row = grid.size();
6+
int col = grid[0].size();
7+
8+
queue<pair<int,int>> q;
9+
vector<vector<int>> ans(row,vector<int>(col,-1));
10+
11+
for(int i=0;i<row;i++)
12+
{
13+
for(int j=0;j<col;j++)
14+
{
15+
if(grid[i][j]==1) {
16+
q.push({i,j});
17+
ans[i][j]=0;
18+
}
19+
}
20+
}
21+
int dx[] = {0, 0, 1, -1};
22+
int dy[] = {1, -1, 0 , 0};
23+
24+
int level=0;
25+
26+
while(!q.empty())
27+
{
28+
int size = q.size();
29+
for(int i=0;i<size;i++) {
30+
int a = q.front().first;
31+
int b = q.front().second;
32+
q.pop();
33+
34+
for(int k=0;k<4;k++)
35+
{
36+
int na = a+dx[k];
37+
int nb = b+dy[k];
38+
39+
if(na<0||nb<0||na>=row||nb>=col||ans[na][nb]!=-1) continue;
40+
q.push({na,nb});
41+
ans[na][nb]=ans[a][b]+1;
42+
}
43+
}
44+
}
45+
return ans;
46+
}
47+
};

0 commit comments

Comments
 (0)