Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[pull] master from youngyangyang04:master #457

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
jenningsloy318 merged 7 commits into AlgorithmAndLeetCode:master from youngyangyang04:master
Jun 17, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
更新417Java DFS跟Carl C++代码思路更一致的版本
  • Loading branch information
lesleyzhao committed Jun 16, 2024
commit 51f7960963061ad15bde0ff90067913d62b960ca
67 changes: 67 additions & 0 deletions problems/0417.太平洋大西洋水流问题.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

AltStyle によって変換されたページ (->オリジナル) /