-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAs Far From Land Possible.cpp
55 lines (46 loc) · 1.6 KB
/
As Far From Land 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
class Solution {
public:
int maxDistance(vector<vector<int>>& grid) {
//initializing helping variables
int n = grid.size();
int res = -1;
//initializing queue for
queue<pair<pair<int,int>,int>> q;
//initializing utility matrix for BFS
vector<vector<int>> util(n , vector<int> (n,-1));
//these two vectors for traversing nodes as (left,up,right,down)
vector<int> drow {0,-1,0,1};
vector<int> dcol {-1,0,1,0};
//pushing all land nodes in queue with initial distance as 0
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
if(grid[i][j]==1) {
q.push({{i,j},0});
util[i][j] = 0;
}
}
}
// BFS
while(!q.empty()) {
auto t = q.front();
q.pop();
int r = t.first.first;
int c = t.first.second;
int d = t.second;
for(int i=0; i<4; i++) {
int dr = r + drow[i];
int dc = c + dcol[i];
//checking is its an unvisited water node or not.
if(dr>=0&&dr<n&&dc>=0&&dc<n&&grid[dr][dc]==0&&util[dr][dc]==-1) {
q.push({{dr,dc},d+1});
util[dr][dc] = d+1;
//updating our res(maximum distnace) if possible
if(d+1!=0) {
res = max(res,d+1);
}
}
}
}
return res;
}
};