更新417Java DFS跟Carl C++代码思路更一致的版本

This commit is contained in:
lesleyzhao
2024-06-16 13:50:09 +08:00
parent 1d206949dd
commit 51f7960963

View File

@ -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<List<Integer>> 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<m; i++){
dfs(heights, pacific, i, 0); //遍历pacific最左边
dfs(heights, atlantic, i, n-1); //遍历atlantic最右边
}
// 从最上最下行的节点出发,向高处遍历
for(int j = 0; j<n; j++){
dfs(heights, pacific, 0, j); //遍历pacific最上边
dfs(heights, atlantic, m-1, j); //遍历atlantic最下边
}
List<List<Integer>> result = new ArrayList<>();
for(int a = 0; a<m; a++){
for(int b = 0; b<n; b++){
// 如果这个节点,从太平洋和大西洋出发都遍历过,就是结果
if(pacific[a][b] && atlantic[a][b]){
List<Integer> pair = new ArrayList<>();
pair.add(a);
pair.add(b);
result.add(pair);
}
}
}
return result;
}
}
```
广度优先遍历:
```Java