File tree Expand file tree Collapse file tree 1 file changed +63
-0
lines changed
pacific-atlantic-water-flow Expand file tree Collapse file tree 1 file changed +63
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {number[][] } heights
3+ * @return {number[][] }
4+ */
5+ var pacificAtlantic = function ( heights ) {
6+ const m = heights . length ,
7+ n = heights [ 0 ] . length ;
8+ let result = [ ] ;
9+
10+ const pacific = new Array ( m ) . fill ( null ) . map ( ( ) => new Array ( n ) . fill ( false ) ) ;
11+ const atlantic = new Array ( m ) . fill ( null ) . map ( ( ) => new Array ( n ) . fill ( false ) ) ;
12+
13+ const dir = [
14+ [ 0 , 1 ] ,
15+ [ 1 , 0 ] ,
16+ [ 0 , - 1 ] ,
17+ [ - 1 , 0 ] ,
18+ ] ;
19+
20+ const dfs = ( i , j , ocean ) => {
21+ // Check visited cell
22+ ocean [ i ] [ j ] = true ;
23+
24+ for ( d of dir ) {
25+ let x = i + d [ 0 ] ,
26+ y = j + d [ 1 ] ;
27+ if (
28+ x >= 0 &&
29+ x < m &&
30+ y >= 0 &&
31+ y < n &&
32+ ! ocean [ x ] [ y ] &&
33+ heights [ x ] [ y ] >= heights [ i ] [ j ]
34+ ) {
35+ dfs ( x , y , ocean ) ;
36+ }
37+ }
38+ } ;
39+
40+ // Check the cells can flow left and right edge
41+ for ( let i = 0 ; i < m ; i ++ ) {
42+ dfs ( i , 0 , pacific ) ;
43+ dfs ( i , n - 1 , atlantic ) ;
44+ }
45+
46+ // Check the cells can flow top and bottom edge
47+ for ( let j = 0 ; j < n ; j ++ ) {
48+ dfs ( 0 , j , pacific ) ;
49+ dfs ( m - 1 , j , atlantic ) ;
50+ }
51+
52+ for ( let i = 0 ; i < m ; i ++ ) {
53+ for ( let j = 0 ; j < n ; j ++ ) {
54+ if ( pacific [ i ] [ j ] && atlantic [ i ] [ j ] ) {
55+ result . push ( [ i , j ] ) ;
56+ }
57+ }
58+ }
59+ return result ;
60+ } ;
61+
62+ // TC: O(m*n)
63+ // SC: O(m*n)
You can’t perform that action at this time.
0 commit comments