diff --git a/problems/0417.太平洋大西洋水流问题.md b/problems/0417.太平洋大西洋水流问题.md index b8448e93..5156ce22 100644 --- a/problems/0417.太平洋大西洋水流问题.md +++ b/problems/0417.太平洋大西洋水流问题.md @@ -177,14 +177,14 @@ public: // 记录从大西洋出发,可以遍历的节点 vector> atlantic = vector>(n, vector(m, false)); - - // 从最上最下行的节点出发,向高处遍历 + + // 从最左最右列的节点出发,向高处遍历 for (int i = 0; i < n; i++) { dfs (heights, pacific, i, 0); // 遍历最左列,接触太平洋 dfs (heights, atlantic, i, m - 1); // 遍历最右列,接触大西 } - // 从最左最右列的节点出发,向高处遍历 + // 从最上最下行的节点出发,向高处遍历 for (int j = 0; j < m; j++) { dfs (heights, pacific, 0, j); // 遍历最上行,接触太平洋 dfs (heights, atlantic, n - 1, j); // 遍历最下行,接触大西洋 @@ -297,6 +297,73 @@ class Solution { } ``` +```Java +class Solution { + + // 和Carl题解更加符合的Java DFS + private int[][] directions = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}}; + + /** + * @param heights 题目给定的二维数组 + * @param m 当前位置的行号 + * @param n 当前位置的列号 + * @param visited 记录这个位置可以到哪条河 + */ + + public void dfs(int[][] heights, boolean[][] visited, int m, int n){ + if(visited[m][n]) return; + visited[m][n] = true; + + for(int[] dir: directions){ + int nextm = m + dir[0]; + int nextn = n + dir[1]; + //出了2D array的边界,continue + if(nextm < 0||nextm == heights.length||nextn <0||nextn== heights[0].length) continue; + //下一个位置比当下位置还要低,跳过,继续找下一个更高的位置 + if(heights[m][n] > heights[nextm][nextn]) continue; + dfs(heights, visited, nextm, nextn); + } + } + + + public List> pacificAtlantic(int[][] heights) { + int m = heights.length; + int n = heights[0].length; + + // 记录从太平洋边出发,可以遍历的节点 + boolean[][] pacific = new boolean[m][n]; + // 记录从大西洋出发,可以遍历的节点 + boolean[][] atlantic = new boolean[m][n]; + + // 从最左最右列的节点出发,向高处遍历 + for(int i = 0; i> result = new ArrayList<>(); + for(int a = 0; a pair = new ArrayList<>(); + pair.add(a); + pair.add(b); + result.add(pair); + } + } + } + return result; + } +} +``` + 广度优先遍历: ```Java