From 1d206949dd3649f997868536b66b0d268e365965 Mon Sep 17 00:00:00 2001 From: lesleyzhao Date: Sun, 16 Jun 2024 13:27:11 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E6=9B=B4=E6=96=B0417=E4=B8=ADCarl=E9=A2=98?= =?UTF-8?q?=E8=A7=A3C++=E4=BB=A3=E7=A0=81=E9=87=8C=E7=9A=84=E6=B3=A8?= =?UTF-8?q?=E9=87=8A=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0417.太平洋大西洋水流问题.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/problems/0417.太平洋大西洋水流问题.md b/problems/0417.太平洋大西洋水流问题.md index b8448e93..5218b571 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); // 遍历最下行,接触大西洋 From 51f7960963061ad15bde0ff90067913d62b960ca Mon Sep 17 00:00:00 2001 From: lesleyzhao Date: Sun, 16 Jun 2024 13:50:09 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E6=9B=B4=E6=96=B0417Java=20DFS=E8=B7=9FCar?= =?UTF-8?q?l=20C++=E4=BB=A3=E7=A0=81=E6=80=9D=E8=B7=AF=E6=9B=B4=E4=B8=80?= =?UTF-8?q?=E8=87=B4=E7=9A=84=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0417.太平洋大西洋水流问题.md | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/problems/0417.太平洋大西洋水流问题.md b/problems/0417.太平洋大西洋水流问题.md index 5218b571..5156ce22 100644 --- a/problems/0417.太平洋大西洋水流问题.md +++ b/problems/0417.太平洋大西洋水流问题.md @@ -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