Skip to content

Commit 6d8b040

Browse files
Create pacific_atlantic_water_flow.cpp
1 parent 7dcdd8c commit 6d8b040

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

pacific_atlantic_water_flow.cpp

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
class Solution {
2+
public:
3+
vector<vector<int>> drs{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
4+
int rows = 0;
5+
int cols = 0;
6+
7+
void dfs(int ix, int jy, pair<int, int> prev, vector<vector<bool>> &visited, vector<vector<int>> &heights)
8+
{
9+
if (ix < 0 || ix >= rows || jy < 0 || jy >= cols || visited[ix][jy])
10+
return;
11+
if (heights[prev.first][prev.second] >heights[ix][jy])
12+
return;
13+
14+
visited[ix][jy] = true;
15+
16+
for (auto &c : drs)
17+
{
18+
dfs(ix+c[0],jy+c[1],{ix, jy}, visited, heights);
19+
}
20+
}
21+
22+
vector<vector<int>> pacificAtlantic(vector<vector<int>> &heights)
23+
{
24+
rows = heights.size();
25+
cols = heights[0].size();
26+
27+
vector<vector<bool>> pacific_drain_visited(rows, vector<bool>(cols, false));
28+
vector<vector<bool>> atlantic_drain_visited(rows, vector<bool>(cols, false));
29+
30+
int j = 0;
31+
while (j < cols) {
32+
dfs(0, j, {0, j}, pacific_drain_visited, heights);
33+
dfs(rows - 1, j, {rows - 1, j}, atlantic_drain_visited, heights);
34+
j++;
35+
}
36+
37+
int i = 0;
38+
while (i < rows) {
39+
dfs(i, 0, {i, 0}, pacific_drain_visited, heights);
40+
dfs(i, cols - 1, {i, cols - 1}, atlantic_drain_visited, heights);
41+
i++;
42+
}
43+
44+
vector<vector<int>> result;
45+
for (int i = 0; i < rows; i++) {
46+
for (int j = 0; j < cols; j++) {
47+
if (pacific_drain_visited[i][j] && atlantic_drain_visited[i][j])
48+
result.push_back({i, j});
49+
}
50+
}
51+
return result;
52+
}
53+
};

0 commit comments

Comments
 (0)