class Solution {
private int[][] direction = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
public List<List<Integer>> pacificAtlantic(int[][] grid) {
List<List<Integer>> list = new ArrayList<>();
int[][] recLU = new int[grid.length][grid[0].length];
int[][] recRD = new int[grid.length][grid[0].length];
//分为4面进行
for (int i = 0; i < grid.length; i++) {
dfs(i, 0, recLU, grid);
dfs(i, grid[0].length - 1, recRD, grid);
}
for (int i = 0; i < grid[0].length; i++) {
dfs(0, i, recLU, grid);
dfs(grid.length - 1, i, recRD, grid);
}
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if ((recLU[i][j] == 1) && (recRD[i][j] == 1)) {
List<Integer> list0 = new ArrayList<Integer>();
list0.add(i);
list0.add(j);
list.add(list0);
}
}
}
return list;
}
public void dfs(int r, int c, int[][] canReach, int[][] grid) {
//从海边出发,凡是能到达的点即可到达对应的海洋
if (canReach[r][c] == 1) {
return;
}
canReach[r][c] = 1;
for (int[] d : direction) {
//先判断下一方向是否合法
int nextR = d[0] + r;
int nextC = d[1] + c;
if (nextR < 0 || nextR > grid.length - 1 || nextC < 0 || nextC > grid[0].length - 1) {
continue;
}
if (grid[r][c] <= grid[nextR][nextC]) {
dfs(nextR, nextC, canReach, grid);
}
}
}
}
DFS LeetCode 417
最新推荐文章于 2024-11-11 20:59:17 发布
该篇博客介绍了一个使用深度优先搜索(DFS)算法解决如何找到一个二维网格中同时能到达太平洋和大西洋的所有点的问题。通过创建两个辅助数组记录每个点能否分别从左侧和右侧、上侧和下侧到达海洋,最后找出同时能到达两者的所有点并返回其坐标。
摘要由CSDN通过智能技术生成