Skip to content

Commit debae3b

Browse files
Implement Pacific Atlantic Water Flow algorithm
1 parent 3c06f02 commit debae3b

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
class PacificAtlanticWaterFlow {
2+
public List<List<Integer>> pacificAtlantic(int[][] heights) {
3+
int n = heights.length;
4+
int m = heights[0].length;
5+
6+
boolean[][] canReachPacific = new boolean[n][m];
7+
boolean[][] canReachAtlantic = new boolean[n][m];
8+
9+
List<List<Integer>> result = new ArrayList<>();
10+
11+
for(int i = 0; i<n; i++){
12+
for(int j = 0; j<m; j++){
13+
if(i == 0){
14+
dfs(i, j, m, n, canReachPacific, heights);
15+
}
16+
if(j == 0){
17+
dfs(i, j, m, n, canReachPacific, heights);
18+
}
19+
if(i == n-1){
20+
dfs(i, j, m, n, canReachAtlantic, heights);
21+
}
22+
if(j == m-1){
23+
dfs(i, j, m, n, canReachAtlantic, heights);
24+
}
25+
}
26+
}
27+
28+
for(int i = 0; i<n; i++){
29+
for(int j = 0; j<m; j++){
30+
if(canReachPacific[i][j] == true && canReachAtlantic[i][j] == true){
31+
List<Integer> coordinates = new ArrayList<>();
32+
coordinates.add(i);
33+
coordinates.add(j);
34+
result.add(coordinates);
35+
}
36+
}
37+
}
38+
39+
return result;
40+
41+
}
42+
43+
static void dfs(int i, int j, int m, int n, boolean[][] visited, int[][] heights){
44+
if(i<0 || j<0 || i>=n || j>=m){
45+
return;
46+
}
47+
48+
if(visited[i][j] == true){
49+
return;
50+
}
51+
52+
visited[i][j] = true;
53+
54+
// up
55+
if (i - 1 >= 0 && heights[i - 1][j] >= heights[i][j]) {
56+
dfs(i - 1, j, m, n, visited, heights);
57+
}
58+
// down
59+
if (i + 1 < n && heights[i + 1][j] >= heights[i][j]) {
60+
dfs(i + 1, j, m, n, visited, heights);
61+
}
62+
// left
63+
if (j - 1 >= 0 && heights[i][j - 1] >= heights[i][j]) {
64+
dfs(i, j - 1, m, n, visited, heights);
65+
}
66+
// right
67+
if (j + 1 < m && heights[i][j + 1] >= heights[i][j]) {
68+
dfs(i, j + 1, m, n, visited, heights);
69+
}
70+
}
71+
}

0 commit comments

Comments
 (0)