Skip to content

Commit fa8af06

Browse files
committed
Pacific Atlantic Water Flow solution
1 parent cc59335 commit fa8af06

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution {
2+
public:
3+
void dfs(int prev, int r, int c, vector<vector<int>>& heights, vector<vector<bool>>& visit){
4+
if(r < 0 || c < 0 || r >= heights.size() || c >= heights[0].size() || visit[r][c] || heights[r][c] < prev)
5+
return;
6+
7+
visit[r][c] = true;
8+
9+
dfs(heights[r][c], r - 1, c, heights, visit);
10+
dfs(heights[r][c], r + 1, c, heights, visit);
11+
dfs(heights[r][c], r, c - 1, heights, visit);
12+
dfs(heights[r][c], r, c + 1, heights, visit);
13+
}
14+
15+
vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
16+
vector<vector<int>> result;
17+
vector<vector<bool>> pacific(heights.size(), vector(heights[0].size(), false));
18+
vector<vector<bool>> atlantic(heights.size(), vector(heights[0].size(), false));
19+
20+
for(int i = 0; i < heights.size(); i++){
21+
dfs(heights[i][0], i, 0, heights, pacific);
22+
dfs(heights[i][heights[0].size()-1], i, heights[0].size()-1, heights, atlantic);
23+
}
24+
25+
for(int j = 0; j < heights[0].size(); j++){
26+
dfs(heights[0][j], 0, j, heights, pacific);
27+
dfs(heights[heights.size()-1][j], heights.size()-1, j, heights, atlantic);
28+
}
29+
30+
for(int i = 0; i < heights.size(); i++){
31+
for(int j = 0; j < heights[0].size(); j++){
32+
if(pacific[i][j] && atlantic[i][j]){
33+
result.push_back({i, j});
34+
}
35+
}
36+
}
37+
38+
return result;
39+
}
40+
};

0 commit comments

Comments
 (0)