-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1162. As Far from Land as Possible
38 lines (33 loc) · 1.07 KB
/
1162. As Far from Land as Possible
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
//https://leetcode.com/problems/as-far-from-land-as-possible/
class Solution {
public:
void dfs(vector<vector<int>>& grid ,int i,int j ,int dist, bool l = false){
if(!l){
if(i<0 || i>grid.size() || j<0 || j>grid.size() || (grid[i][j]<=dist && grid[i][j]!=0 ))
return;
grid[i][j] = dist;
}
dfs(grid,i+1,j,dist+1);
dfs(grid,i-1,j,dist+1);
dfs(grid,i,j+1,dist+1);
dfs(grid,i,j-1,dist+1);
}
int maxDistance(vector<vector<int>>& grid) {
for(int i = 0 ; i<grid.size() ; i++){
for(int j = 0 ; j<grid[i].size() ; j++){
if(grid[i][j] == 1)
dfs(grid,i,j,1,true);
}
}
int mx = -1;
for(int i = 0 ; i<grid.size() ; i++){
for(int j = 0 ; j<grid[0].size() ; j++){
cout<<grid[i][j]<<" ";
if(grid[i][j] > 1) mx = max(mx,grid[i][j]);
}
cout<<endl;
}
if(mx == -1) return -1;
return mx-1;
}
};