Skip to content

Commit a9ffe33

Browse files
authored
2022-08-31 update: added "Pacific Atlantic Water Flow" (#78)
1 parent 79630ba commit a9ffe33

File tree

2 files changed

+94
-0
lines changed

2 files changed

+94
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.smlnskgmail.jaman.leetcodejava.medium;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
7+
// https://leetcode.com/problems/pacific-atlantic-water-flow/
8+
public class PacificAtlanticWaterFlow {
9+
10+
private final int[][] input;
11+
12+
public PacificAtlanticWaterFlow(int[][] input) {
13+
this.input = input;
14+
}
15+
16+
public List<List<Integer>> solution() {
17+
int r = input.length;
18+
int c = input[0].length;
19+
boolean[][] atlantic = new boolean[r][c];
20+
boolean[][] pacific = new boolean[r][c];
21+
for (int i = 0; i < r; i++) {
22+
for (int j = 0; j < c; j++) {
23+
if (i == 0 || j == 0) {
24+
dfs(pacific, input, i, j, 0);
25+
}
26+
if (i == r - 1 || j == c - 1) {
27+
dfs(atlantic, input, i, j, 0);
28+
}
29+
}
30+
}
31+
List<List<Integer>> result = new ArrayList<>();
32+
for (int i = 0; i < r; i++) {
33+
for (int j = 0; j < c; j++) {
34+
if (atlantic[i][j] && pacific[i][j]) {
35+
result.add(Arrays.asList(i, j));
36+
}
37+
}
38+
}
39+
return result;
40+
}
41+
42+
private void dfs(boolean[][] sea, int[][] grid, int r, int c, int prev) {
43+
if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length) {
44+
return;
45+
}
46+
if (grid[r][c] < prev) {
47+
return;
48+
}
49+
if (sea[r][c]) {
50+
return;
51+
}
52+
sea[r][c] = true;
53+
dfs(sea, grid, r + 1, c, grid[r][c]);
54+
dfs(sea, grid, r - 1, c, grid[r][c]);
55+
dfs(sea, grid, r, c + 1, grid[r][c]);
56+
dfs(sea, grid, r, c - 1, grid[r][c]);
57+
}
58+
59+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.smlnskgmail.jaman.leetcodejava.medium;
2+
3+
import org.junit.Test;
4+
5+
import java.util.List;
6+
7+
import static org.junit.Assert.assertEquals;
8+
9+
public class PacificAtlanticWaterFlowTest {
10+
11+
@Test
12+
public void defaultTest() {
13+
assertEquals(
14+
List.of(
15+
List.of(0, 4),
16+
List.of(1, 3),
17+
List.of(1, 4),
18+
List.of(2, 2),
19+
List.of(3, 0),
20+
List.of(3, 1),
21+
List.of(4, 0)
22+
),
23+
new PacificAtlanticWaterFlow(
24+
new int[][]{
25+
{1, 2, 2, 3, 5},
26+
{3, 2, 3, 4, 4},
27+
{2, 4, 5, 3, 1},
28+
{6, 7, 1, 4, 5},
29+
{5, 1, 1, 2, 4}
30+
}
31+
).solution()
32+
);
33+
}
34+
35+
}

0 commit comments

Comments
 (0)