leetcode417

DFS ideas

 1 class Solution {
 2     private int m, n;
 3     private int[][] matrix;
 4     private int[][] direction = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
 5 
 6     public List<int[]> pacificAtlantic(int[][] matrix) {
 7         List<int[]> ret = new ArrayList<>();
 8         if (matrix == null || matrix.length == 0) {
 9             return ret;
10         }
11 
12         m = matrix.length;
13         n = matrix[0].length;
14         this.matrix = matrix;
15         boolean[][] canReachP = new boolean[m][n];
16         boolean[][] canReachA = new boolean[m][n];
17 
18         for (int i = 0; i < m; i++) {
19             DFS (I, 0 , canReachP); // from the left border (Pacific) begins, i.e., 0th column 
20 is              DFS (I, n-- . 1 , canReachA); // right boundary (Atlantic) begins, i.e., the last column 
21          }
 22 is          for ( int I = 0 ; I <n-; I ++ ) {
 23 is              DFS ( 0 , I, canReachP); // start from the boundary (Pacific), i.e., the 0th row 
24              DFS (m - . 1 , I, canReachA) ; // from the lower boundary (Atlantic), i.e., the last line 
25          }
 26 is  
27          for ( int I = 0; I <m; I ++ ) {
 28              for ( int J = 0 ; J <n-; J ++ ) {
 29                  IF (canReachP [I] [J] && canReachA [I] [J]) { // simultaneously from Pacific boundary and a point (intersection of) reaches the boundary of the Atlantic 
30                      ret.add ( new new  int [] {I, J});
 31 is                  }
 32              }
 33 is          }
 34 is  
35          return RET;
 36      }
 37 [  
38 is      Private  void DFS ( int R & lt, int C , Boolean [] [] canReach) {
 39          IF(canReach [R & lt] [C]) {
 40              return ;
 41 is          }
 42 is          canReach [R & lt] [C] = to true ;
 43 is          for ( int [] D: direction) { // traverse up and down, four directions 
44 is              int nextR = D [ 0 ] + R & lt;
 45              int NEXTC = D [ . 1 ] + C;
 46 is              IF (nextR < 0 || nextR> = m || NEXTC < 0 || NEXTC> = n- // bounds (illegal) 
47                      || Matrix [R & lt] [C]> Matrix [nextR] [NEXTC]) { //From above (boundaries of) the lower flow (central region) (illegal) 
48  
49                  Continue ;
 50              }
 51 is              DFS (nextR, NEXTC, canReach);
 52 is          }
 53 is      }
 54 is }

 

Guess you like

Origin www.cnblogs.com/asenyang/p/10992544.html