给定一个 m x n 的非负整数矩阵来表示一片大陆上各个单元格的高度。“太平洋”处于大陆的左边界和上边界,而“大西洋”处于大陆的右边界和下边界。
    规定水流只能按照上、下、左、右四个方向流动,且只能从高到低或者在同等高度上流动。
    请找出那些水流既可以流动到“太平洋”,又能流动到“大西洋”的陆地单元的坐标。

    提示:
    输出坐标的顺序不重要
    m 和 n 都小于150
    示例:
    给定下面的 5x5 矩阵:

    太平洋 ~ ~ ~ ~ ~
    ~ 1 2 2 3 (5)
    ~ 3 2 3 (4) (4)

    ~ 2 4 (5) 3 1
    ~ (6) (7) 1 4 5

    ~ (5) 1 1 2 4
    大西洋
    返回:
    [[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (上图中带括号的单元).
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/pacific-atlantic-water-flow


    思路:
    还是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. public List<List<Integer>> pacificAtlantic(int[][] matrix) {
    6. List<List<Integer>> ret = new ArrayList<>();
    7. if (matrix == null || matrix.length == 0) {
    8. return ret;
    9. }
    10. m = matrix.length;
    11. n = matrix[0].length;
    12. this.matrix = matrix;
    13. boolean[][] canReachP = new boolean[m][n];
    14. boolean[][] canReachA = new boolean[m][n];
    15. for (int i = 0; i < m; i++) {
    16. dfs(i, 0, canReachP);
    17. dfs(i, n - 1, canReachA);
    18. }
    19. for (int i = 0; i < n; i++) {
    20. dfs(0, i, canReachP);
    21. dfs(m - 1, i, canReachA);
    22. }
    23. for (int i = 0; i < m; i++) {
    24. for (int j = 0; j < n; j++) {
    25. if (canReachP[i][j] && canReachA[i][j]) {
    26. ret.add(Arrays.asList(i, j));
    27. }
    28. }
    29. }
    30. return ret;
    31. }
    32. private void dfs(int r, int c, boolean[][] canReach) {
    33. if (canReach[r][c]) {
    34. return;
    35. }
    36. canReach[r][c] = true;
    37. for (int[] d : direction) {
    38. int nextR = d[0] + r;
    39. int nextC = d[1] + c;
    40. if (nextR < 0 || nextR >= m || nextC < 0 || nextC >= n
    41. || matrix[r][c] > matrix[nextR][nextC]) {
    42. continue;
    43. }
    44. dfs(nextR, nextC, canReach);
    45. }
    46. }
    47. }