-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1162. As Far from Land as Possible.cpp
50 lines (44 loc) · 1.91 KB
/
1162. 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
/*
Problem : https://leetcode.com/problems/as-far-from-land-as-possible/
Author : Sabbir Musfique
Time Complexity : O(N*N)
Space Complexity : O(1)
*/
class Solution {
public:
int maxDistance(vector<vector<int>>& grid) {
int rows = grid.size();
// Although it's a square matrix, using different variable for readability.
int cols = grid[0].size();
// Maximum manhattan distance possible + 1.
const int MAX_DISTANCE = rows + cols + 1;
// First pass: check for left and top neighbours
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (grid[i][j]) {
// Distance of land cells will be 0.
grid[i][j] = 0;
} else {
grid[i][j] = MAX_DISTANCE;
// Check left and top cell distances if they exist and update the current cell distance.
grid[i][j] = min(grid[i][j], min(i > 0 ? grid[i - 1][j] + 1 : MAX_DISTANCE,
j > 0 ? grid[i][j - 1] + 1 : MAX_DISTANCE));
}
}
}
// Second pass: check for right and bottom neighbours.
int ans = INT_MIN;
for (int i = rows - 1; i >= 0; i--) {
for (int j = cols - 1; j >= 0; j--) {
// Check the right and bottom cell distances if they exist and update the current cell distance.
grid[i][j] = min(grid[i][j], min(i < rows - 1 ? grid[i + 1][j] + 1 : MAX_DISTANCE,
j < cols - 1 ? grid[i][j + 1] + 1 : MAX_DISTANCE));
ans = max(ans, grid[i][j]);
}
}
// If ans is 1, it means there is no water cell,
// If ans is MAX_DISTANCE, it implies no land cell.
return ans == 0 || ans == MAX_DISTANCE ? -1 : ans;
}
//sabbir
};