-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpacificAtlantic.java
More file actions
40 lines (35 loc) · 1.36 KB
/
pacificAtlantic.java
File metadata and controls
40 lines (35 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
public List<List<Integer>> pacificAtlantic(int[][] heights) {
int m = heights.length, n = heights[0].length;
boolean[][] pacific = new boolean[m][n];
boolean[][] atlantic = new boolean[m][n];
for (int i = 0; i < m; i++) {
dfs(heights, pacific, i, 0, -1);
dfs(heights, atlantic, i, n - 1, -1);
}
for (int j = 0; j < n; j++) {
dfs(heights, pacific, 0, j, -1);
dfs(heights, atlantic, m - 1, j, -1);
}
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (pacific[i][j] && atlantic[i][j]) {
result.add(Arrays.asList(i, j));
}
}
}
return result;
}
private void dfs(int[][] heights, boolean[][] visited, int i, int j, int prevHeight) {
int m = heights.length, n = heights[0].length;
if (i < 0 || j < 0 || i >= m || j >= n) return;
if (visited[i][j]) return;
if (heights[i][j] < prevHeight) return;
visited[i][j] = true;
dfs(heights, visited, i + 1, j, heights[i][j]);
dfs(heights, visited, i - 1, j, heights[i][j]);
dfs(heights, visited, i, j + 1, heights[i][j]);
dfs(heights, visited, i, j - 1, heights[i][j]);
}
}