leetcode417
Posted asenyang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
以上是关于leetcode417的主要内容,如果未能解决你的问题,请参考以下文章
[JavaScript 刷题] 搜索 - 太平洋大西洋水流问题, leetcode 417
LeetCode 417. 太平洋大西洋水流问题(多源bfs) / 905. 按奇偶排序数组 / 427. 建立四叉树(dfs+二维前缀和)