1
+ class Solution {
2
+ public:
3
+ void dfs (vector<vector<int >>& h, vector<vector<bool >>& vis, int i, int j) {
4
+
5
+ int m = h.size ();
6
+ int n = h[0 ].size ();
7
+
8
+ vis[i][j] = true ;
9
+ // up
10
+ if (i-1 >= 0 && vis[i-1 ][j] != true && h[i-1 ][j] >= h[i][j])
11
+ dfs (h, vis, i-1 , j);
12
+ // down
13
+ if (i+1 < m && vis[i+1 ][j] != true && h[i+1 ][j] >= h[i][j])
14
+ dfs (h, vis, i+1 , j);
15
+ // left
16
+ if (j-1 >= 0 && vis[i][j-1 ] != true && h[i][j-1 ] >= h[i][j])
17
+ dfs (h, vis, i, j-1 );
18
+ // right
19
+ if (j+1 < n && vis[i][j+1 ] != true && h[i][j+1 ] >= h[i][j])
20
+ dfs (h, vis, i, j+1 );
21
+
22
+ }
23
+
24
+ vector<vector<int >> pacificAtlantic (vector<vector<int >>& heights) {
25
+
26
+ vector<vector<int >>ans;
27
+ int m = heights.size ();
28
+ int n = heights[0 ].size ();
29
+
30
+ vector<vector<bool >> pacific (m, vector<bool >(n));
31
+ vector<vector<bool >> atlantic (m, vector<bool >(n));
32
+
33
+ for (int i = 0 ; i < m; i++) {
34
+
35
+ dfs (heights, pacific, i, 0 );
36
+ dfs (heights, atlantic, i, n-1 );
37
+
38
+ }
39
+
40
+ for (int j = 0 ; j < n; j++) {
41
+
42
+ dfs (heights, pacific, 0 , j);
43
+ dfs (heights, atlantic, m-1 , j);
44
+ }
45
+
46
+
47
+ for (int i = 0 ; i < m; i++) {
48
+ for (int j = 0 ; j < n; j++) {
49
+ if (pacific[i][j] && atlantic[i][j]) ans.push_back ({i,j});
50
+ }
51
+ }
52
+ return ans;
53
+ }
54
+
55
+ };
0 commit comments