@@ -177,14 +177,14 @@ public:
177177
178178 // 记录从大西洋出发,可以遍历的节点
179179 vector<vector<bool>> atlantic = vector<vector<bool>>(n, vector<bool>(m, false));
180-
181- // 从最上最下行的节点出发 ,向高处遍历
180+
181+ // 从最左最右列的节点出发 ,向高处遍历
182182 for (int i = 0; i < n; i++) {
183183 dfs (heights, pacific, i, 0); // 遍历最左列,接触太平洋
184184 dfs (heights, atlantic, i, m - 1); // 遍历最右列,接触大西
185185 }
186186
187- // 从最左最右列的节点出发 ,向高处遍历
187+ // 从最上最下行的节点出发 ,向高处遍历
188188 for (int j = 0; j < m; j++) {
189189 dfs (heights, pacific, 0, j); // 遍历最上行,接触太平洋
190190 dfs (heights, atlantic, n - 1, j); // 遍历最下行,接触大西洋
@@ -297,6 +297,73 @@ class Solution {
297297}
298298```
299299
300+ ``` Java
301+ class Solution {
302+
303+ // 和Carl题解更加符合的Java DFS
304+ private int [][] directions = {{- 1 , 0 }, {1 , 0 }, {0 , 1 }, {0 , - 1 }};
305+
306+ /**
307+ * @param heights 题目给定的二维数组
308+ * @param m 当前位置的行号
309+ * @param n 当前位置的列号
310+ * @param visited 记录这个位置可以到哪条河
311+ */
312+
313+ public void dfs (int [][] heights , boolean [][] visited , int m , int n ){
314+ if (visited[m][n]) return ;
315+ visited[m][n] = true ;
316+
317+ for (int [] dir: directions){
318+ int nextm = m + dir[0 ];
319+ int nextn = n + dir[1 ];
320+ // 出了2D array的边界,continue
321+ if (nextm < 0 || nextm == heights. length|| nextn < 0 || nextn== heights[0 ]. length) continue ;
322+ // 下一个位置比当下位置还要低,跳过,继续找下一个更高的位置
323+ if (heights[m][n] > heights[nextm][nextn]) continue ;
324+ dfs(heights, visited, nextm, nextn);
325+ }
326+ }
327+
328+
329+ public List<List<Integer > > pacificAtlantic (int [][] heights ) {
330+ int m = heights. length;
331+ int n = heights[0 ]. length;
332+
333+ // 记录从太平洋边出发,可以遍历的节点
334+ boolean [][] pacific = new boolean [m][n];
335+ // 记录从大西洋出发,可以遍历的节点
336+ boolean [][] atlantic = new boolean [m][n];
337+
338+ // 从最左最右列的节点出发,向高处遍历
339+ for (int i = 0 ; i< m; i++ ){
340+ dfs(heights, pacific, i, 0 ); // 遍历pacific最左边
341+ dfs(heights, atlantic, i, n- 1 ); // 遍历atlantic最右边
342+ }
343+
344+ // 从最上最下行的节点出发,向高处遍历
345+ for (int j = 0 ; j< n; j++ ){
346+ dfs(heights, pacific, 0 , j); // 遍历pacific最上边
347+ dfs(heights, atlantic, m- 1 , j); // 遍历atlantic最下边
348+ }
349+
350+ List<List<Integer > > result = new ArrayList<> ();
351+ for (int a = 0 ; a< m; a++ ){
352+ for (int b = 0 ; b< n; b++ ){
353+ // 如果这个节点,从太平洋和大西洋出发都遍历过,就是结果
354+ if (pacific[a][b] && atlantic[a][b]){
355+ List<Integer > pair = new ArrayList<> ();
356+ pair. add(a);
357+ pair. add(b);
358+ result. add(pair);
359+ }
360+ }
361+ }
362+ return result;
363+ }
364+ }
365+ ```
366+
300367广度优先遍历:
301368
302369``` Java
0 commit comments