-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathAs Far from Land as Possible.cpp
60 lines (45 loc) · 1.71 KB
/
As Far from Land as Possible.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
49
50
51
52
53
54
55
56
57
58
59
60
/*
Solution by Rahul Surana
***********************************************************
Given an n x n grid containing only values 0 and 1, where 0 represents water and 1 represents land,
find a water cell such that its distance to the nearest land cell is maximized, and return the distance.
If no land or water exists in the grid, return -1.
The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|.
***********************************************************
*/
#include <bits/stdc++.h>
class Solution {
public:
vector<vector<int>> dp;
int maxDistance(vector<vector<int>>& grid) {
const int n= grid.size();
dp.resize(n,vector<int>(n,0));
int ans = 0;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(grid[i][j] ==1) continue;
dp[i][j] = 1e3;
if(i-1>=0){
dp[i][j] = min(dp[i][j] , 1+ dp[i-1][j]);
}
if(j-1>=0){
dp[i][j] = min(dp[i][j] , 1+ dp[i][j-1]);
}
}
}
for(int i = n-1; i >=0; i--){
for(int j = n-1; j >=0; j--){
if(grid[i][j] ==1) continue;
if(i+1<n){
dp[i][j] = min(dp[i][j] , 1+ dp[i+1][j]);
}
if(j+1<n){
dp[i][j] = min(dp[i][j] , 1+ dp[i][j+1]);
}
ans = max(ans,dp[i][j]);
}
}
// int ans = bfs1(grid);
return ans == 0 || ans == 1e3? -1:ans;
}
};