forked from Chayandas07/LeetCode-challenge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1162. As Far from Land as Possible
36 lines (36 loc) · 1.31 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
class Solution {
public:
int maxDistance(vector<vector<int>>& grid) {
int n = grid.size();
queue<pair<int, int>> q;
//Note: The copy matrix visited can be avoided by updating the original matrix grid but changing the input parameter is not considered under good practices. That's why we are taking extra 2d matrix visited
vector<vector<int>> visited = grid;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (visited[i][j] == 1)
q.push({i, j});
}
}
if (q.empty() || q.size() == n * n)
return -1;
int distance = -1;
// visit all four direction i.e. right, left, up, down
vector<pair<int, int>> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
while (!q.empty()) {
int size = q.size();
while (size--) {
auto [x, y] = q.front();
q.pop();
for (auto [dx, dy] : dirs) {
int i = x + dx, j = y + dy;
if (i >= 0 && i < n && j >= 0 && j < n && visited[i][j] == 0) {
visited[i][j] = 1;
q.push({i, j});
}
}
}
distance++;
}
return distance;
}
};