Skip to content

Commit 3585808

Browse files
committed
Solved Problem of Day 31 (417. Pacific Atlantic Water Flow)
1 parent 5169005 commit 3585808

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

417. Pacific Atlantic Water Flow.cpp

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
class Solution {
2+
public:
3+
void dfs(vector<vector<int>>& h, vector<vector<bool>>& vis, int i, int j) {
4+
5+
int m = h.size();
6+
int n = h[0].size();
7+
8+
vis[i][j] = true;
9+
//up
10+
if (i-1 >= 0 && vis[i-1][j] != true && h[i-1][j] >= h[i][j])
11+
dfs(h, vis, i-1, j);
12+
//down
13+
if (i+1 < m && vis[i+1][j] != true && h[i+1][j] >= h[i][j])
14+
dfs(h, vis, i+1, j);
15+
//left
16+
if (j-1 >= 0 && vis[i][j-1] != true && h[i][j-1] >= h[i][j])
17+
dfs(h, vis, i, j-1);
18+
//right
19+
if (j+1 < n && vis[i][j+1] != true && h[i][j+1] >= h[i][j])
20+
dfs(h, vis, i, j+1);
21+
22+
}
23+
24+
vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
25+
26+
vector<vector<int>>ans;
27+
int m = heights.size();
28+
int n = heights[0].size();
29+
30+
vector<vector<bool>> pacific(m, vector<bool>(n));
31+
vector<vector<bool>> atlantic(m, vector<bool>(n));
32+
33+
for (int i = 0; i < m; i++) {
34+
35+
dfs(heights, pacific, i, 0);
36+
dfs(heights, atlantic, i, n-1);
37+
38+
}
39+
40+
for (int j = 0; j < n; j++) {
41+
42+
dfs(heights, pacific, 0, j);
43+
dfs(heights, atlantic, m-1, j);
44+
}
45+
46+
47+
for (int i = 0; i < m; i++) {
48+
for (int j = 0; j < n; j++) {
49+
if (pacific[i][j] && atlantic[i][j]) ans.push_back({i,j});
50+
}
51+
}
52+
return ans;
53+
}
54+
55+
};

0 commit comments

Comments
 (0)