其他分享
首页 > 其他分享> > leetcode417

leetcode417

作者:互联网

DFS思路

 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);//从左边界(太平洋)开始,即第0列
20             dfs(i, n - 1, canReachA);//从右边界(大西洋)开始,即最后一列
21         }
22         for (int i = 0; i < n; i++) {
23             dfs(0, i, canReachP);//从上边界(太平洋)开始,即第0行
24             dfs(m - 1, i, canReachA);//从下边界(大西洋)开始,即最后一行
25         }
26 
27         for (int i = 0; i < m; i++) {
28             for (int j = 0; j < n; j++) {
29                 if (canReachP[i][j] && canReachA[i][j]) {//同时能从太平洋边界和大西洋边界达到的点(求交集)
30                     ret.add(new int[]{i, j});
31                 }
32             }
33         }
34 
35         return ret;
36     }
37 
38     private void dfs(int r, int c, boolean[][] canReach) {
39         if (canReach[r][c]) {
40             return;
41         }
42         canReach[r][c] = true;
43         for (int[] d : direction) {//遍历上下左右,四个方向
44             int nextR = d[0] + r;
45             int nextC = d[1] + c;
46             if (nextR < 0 || nextR >= m || nextC < 0 || nextC >= n//越界(非法)
47                     || matrix[r][c] > matrix[nextR][nextC]) {//从高处(边界)流向低处(中央区域)(非法)
48 
49                 continue;
50             }
51             dfs(nextR, nextC, canReach);
52         }
53     }
54 }

 

标签:matrix,nextC,int,leetcode417,dfs,boolean,nextR
来源: https://www.cnblogs.com/asenyang/p/10992544.html