@@ -297,6 +297,73 @@ class Solution {
297
297
}
298
298
```
299
299
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
+
300
367
广度优先遍历:
301
368
302
369
``` Java
0 commit comments