Skip to content

Commit 933707a

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add Graphs subfolder
1 parent 8d06643 commit 933707a

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed
File renamed without changes.
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
class Solution {
2+
public List<List<Integer>> pacificAtlantic(int[][] matrix) {
3+
if (matrix == null || matrix.length == 0) {
4+
return Collections.emptyList();
5+
}
6+
7+
List<List<Integer>> result = new ArrayList<>();
8+
int rows = matrix.length, cols = matrix[0].length;
9+
10+
boolean[][] pacificVisited = new boolean[rows][cols];
11+
boolean[][] atlanticVisited = new boolean[rows][cols];
12+
13+
for (int i = 0; i < rows; i++) {
14+
dfs(matrix, i, 0, -1, pacificVisited);
15+
dfs(matrix, i, cols - 1, -1, atlanticVisited);
16+
}
17+
18+
for (int j = 0; j < cols; j++) {
19+
dfs(matrix, 0, j, -1, pacificVisited);
20+
dfs(matrix, rows - 1, j, -1, atlanticVisited);
21+
}
22+
23+
for (int i = 0; i < rows; i++) {
24+
for (int j = 0; j < cols; j++) {
25+
if (pacificVisited[i][j] && atlanticVisited[i][j]) {
26+
result.add(Arrays.asList(i, j));
27+
}
28+
}
29+
}
30+
31+
return result;
32+
}
33+
34+
private void dfs(int[][] matrix, int x, int y, int prevWaterHeight, boolean[][] visited) {
35+
if (x < 0 || y < 0 || x >= matrix.length || y >= matrix[x].length || visited[x][y]
36+
|| prevWaterHeight > matrix[x][y]) {
37+
return;
38+
}
39+
40+
int height = matrix[x][y];
41+
visited[x][y] = true;
42+
43+
dfs(matrix, x - 1, y, height, visited);
44+
dfs(matrix, x + 1, y, height, visited);
45+
dfs(matrix, x, y - 1, height, visited);
46+
dfs(matrix, x, y + 1, height, visited);
47+
48+
return;
49+
}
50+
}

0 commit comments

Comments
 (0)