-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDistance of nearest cell having 1
64 lines (53 loc) · 1.63 KB
/
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
// Distance of nearest cell having 1 - medium - 08/08/2023
class Pair{
int first;
int second;
Pair(int a, int b){
this.first = a;
this.second = b;
}
}
class Solution
{
//Function to find distance of nearest 1 in the grid for each cell.
public int[][] nearest(int[][] grid)
{
int m = grid.length;
int n = grid[0].length;
int[][] ans = new int[m][n];
//boolean[][] vis = new boolean[m][n];
Queue<Pair> q = new LinkedList<>();
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(grid[i][j] == 1){
q.add(new Pair(i,j));
//vis[i][j] = true;
ans[i][j] = 0;
}
else {
ans[i][j] = -1;
}
}
}
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
while(!q.isEmpty()){
int size = q.size();
while(size-- != 0){
int a = q.peek().first;
int b = q.peek().second;
q.remove();
for(int k=0; k<4; k++){
int na = a + dx[k];
int nb = b + dy[k];
if(na<0 || nb<0 || na>=m || nb>=n || ans[na][nb]!=-1){
continue;
}
q.add(new Pair(na, nb));
ans[na][nb] = ans[a][b]+1;
}
}
}
return ans;
}
}