-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathPacificAltaticWaterFlow.java
More file actions
59 lines (43 loc) · 1.57 KB
/
PacificAltaticWaterFlow.java
File metadata and controls
59 lines (43 loc) · 1.57 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class Solution {
//TC O(n2)
// SC O(n2)
public List<List<Integer>> pacificAtlantic(int[][] matrix) {
List<List<Integer>> ans = new ArrayList<>();
if(matrix == null || matrix.length ==0 || matrix[0].length ==0) {
return ans;
}
int m =matrix.length;
int n = matrix[0].length;
boolean[][] pacific = new boolean[m][n];
boolean[][] atlantic = new boolean[m][n];
for(int j=0;j<n;j++){
dfs(0,j, pacific, matrix, Integer.MIN_VALUE);
dfs(m-1, j,atlantic,matrix, Integer.MIN_VALUE);
}
for(int i=0;i<m;i++){
dfs(i,0, pacific, matrix, Integer.MIN_VALUE);
dfs(i, n-1,atlantic,matrix, Integer.MIN_VALUE);
}
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(pacific[i][j] && atlantic[i][j]){
List<Integer> indexes = new ArrayList<>();
indexes.add(i);
indexes.add(j);
ans.add(indexes);
}
}
}
return ans;
}
private void dfs(int i, int j, boolean[][] canReach, int[][] matrix, int prevHeight){
if(i<0 || j<0 || i>=matrix.length || j>=matrix[0].length || canReach[i][j] || matrix[i][j] <prevHeight){
return ;
}
canReach[i][j] = true;
dfs(i+1, j, canReach, matrix, matrix[i][j]);
dfs(i-1, j, canReach, matrix, matrix[i][j]);
dfs(i, j-1, canReach, matrix, matrix[i][j]);
dfs(i, j+1, canReach, matrix, matrix[i][j]);
}
}