leetcode 417. Pacific Atlantic Water Flow

本文介绍了一个寻找可以从给定矩阵中的某些点流向两个不同方向(太平洋和大西洋)的算法问题。利用广度优先搜索(BFS)和深度优先搜索(DFS)两种方法,通过遍历矩阵来找出符合条件的坐标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题目:
Given an m x n matrix of non-negative integers representing the height of each unit cell in a continent, the “Pacific ocean” touches the left and top edges of the matrix and the “Atlantic ocean” touches the right and bottom edges.

Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower.

Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.

Note:

The order of returned grid coordinates does not matter.
Both m and n are less than 150.

Example:

Given the following 5x5 matrix:

Pacific ~ ~ ~ ~ ~
~ 1 2 2 3 (5) *
~ 3 2 3 (4) (4) *
~ 2 4 (5) 3 1 *
~ (6) (7) 1 4 5 *
~ (5) 1 1 2 4 *
* * * * * Atlantic

Return:

[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).

题目说,在每个位置matrix[x][y] 代表这个点的高度, 每个点可以流向等于或者低于自己高度的点。
上面,左面代表 Pacific, 右面,下面代表Atlantic ,求这个matrix里面可以同时流向太平洋,大西洋的坐标集。
一般看到就会想到DFS的解法,我第一次理解错了题意,结果遍历matrix里的每个点, 看是否他能到达两个海洋。最后,超时,思考更完善的算法。
Java BFS

public class Solution {
    int[][] dics = new int[][]{{1,0}, {0,1},{-1,0}, {0,-1}};
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }
    //  这道题明显是可以使用 BFS 或者DFS 来做的,
    // 第一种我才用 广搜
    public List<int[]> pacificAtlantic(int[][] matrix) {
        List<int[]> res = new ArrayList<>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return res;
        }
        int rows = matrix.length;
        int cols = matrix[0].length;
        boolean[][] pacific =  new boolean[rows][cols]; // 记录 可以到达 pacific
        boolean[][] atlantic = new boolean[rows][cols]; // 记录可以到达 atlantic
        Stack<int[]> visitPac = new Stack<>();
        Stack<int[]> visitAtlan = new Stack<>();
        for (int i = 0; i < rows; i++) {
            pacific[i][0] = true;
            visitPac.push(new int[]{i,0});
            atlantic[i][cols - 1] = true;
            visitAtlan.push(new int[]{i,cols - 1});
        }
        for (int j = 0; j < cols; j++) {
            pacific[0][j] = true;
            visitPac.push(new int[]{0,j});
            atlantic[rows - 1][j] = true;
            visitAtlan.push(new int[]{rows - 1, j});
        }
        bfs(matrix, visitPac, pacific);
        bfs(matrix, visitAtlan, atlantic);
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (pacific[i][j] && atlantic[i][j]) {
                    res.add(new int[]{i,j});
                }
            }
        }
        return res;
    }
    public void bfs(int[][] matrix, Stack<int[]> stack, boolean[][] visited) {
        int rows = matrix.length;
        int cols = matrix[0].length;
        while (!stack.isEmpty()) {
            int[] idx = stack.pop();
            for (int[] dic:dics) {
                int x = idx[0] + dic[0];
                int y = idx[1] + dic[1];
                if (x < 0 || x >= rows || y < 0 || y >= cols || visited[x][y] || matrix[x][y] < matrix[idx[0]][idx[1]]) {
                    continue;
                }
                visited[x][y] = true;
                stack.push(new int[]{x,y});
            }
        }
    }
}

后来看到别人提交的DFS版本的答案,DFS 更加好理解。

import java.util.ArrayList;
import java.util.List;

/**
* @author 作者 : coderlong
* @version 创建时间:2018年4月27日 下午2:59:28
* 类说明: 
*/
public class leetcode417_Pactic_Atlantic_water_Flow2 {
    public int[][] dics = {{1,0}, {-1,0}, {0,1}, {0,-1}};
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }
    public List<int[]> pacificAtlantic(int[][] matrix) {
        List<int[]> res = new ArrayList<>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return res;
        }
        int rows = matrix.length;
        int cols = matrix[0].length;

        boolean[][] pacific = new boolean[rows][cols];
        boolean[][] atlantic = new boolean[rows][cols];
        // 用Integer.MIN_VALUE 来访问 四周边界元素, 保证四周元素绝对可以流向visit海域
        for (int i = 0; i < rows; i++) {
            dfs(matrix, Integer.MIN_VALUE, i, 0, pacific);
            dfs(matrix, Integer.MIN_VALUE, i, cols - 1, atlantic);
        }
        for (int j = 0; j < cols; j++) {
            dfs(matrix, Integer.MIN_VALUE, 0, j, pacific);
            dfs(matrix, Integer.MIN_VALUE, rows - 1, j, atlantic);
        }
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (pacific[i][j] && atlantic[i][j]) {
                    res.add(new int[]{i,j});
                }
            }
        }
        return res;
    }
    public void dfs(int[][] matrix, int height, int x, int y, boolean[][]visit) {
        int rows = matrix.length;
        int cols = matrix[0].length;
        // x y 为坐标, 需先判断是否符合要求
        if (x <0 || x >= rows || y < 0 || y >= cols || visit[x][y] || matrix[x][y] < height) {
            return ;
        }
        visit[x][y] = true; // (x,y) 可以流向visit海域
        for (int[] cur : dics) {
            dfs(matrix, matrix[x][y], x + cur[0], y + cur[1], visit);
        }
    }

}
### LeetCode Top 100 经典编程题目 LeetCode 上有许多经典的编程挑战,这些题目被广泛认为是掌握算法和数据结构的关键[^1]。以下是精选的一部分Top 100经典问题列表: #### 数组与字符串 1. **Two Sum** 2. **Add Two Numbers** 3. **Longest Substring Without Repeating Characters** #### 动态规划 4. **Climbing Stairs** 5. **Best Time to Buy and Sell Stock II** 6. **Unique Paths** #### 链表操作 7. **Merge Two Sorted Lists** 8. **Remove Nth Node From End of List** 9. **Reverse Linked List** #### 栈与队列 10. **Valid Parentheses** 11. **Min Stack** 12. **Implement Queue using Stacks** #### 排序与搜索 13. **Search Insert Position** 14. **Find First and Last Position of Element in Sorted Array** 15. **Sort Colors** #### 图论基础 16. **Clone Graph** 17. **Pacific Atlantic Water Flow** 18. **Number of Islands** #### 字符串处理 19. **String to Integer (atoi)** 20. **Valid Number** 21. **Decode Ways** #### 贪心算法 22. **Jump Game** 23. **Gas Station** 24. **Task Scheduler** 以上仅展示了部分LeetCode上被认为是经典的问题。对于完整的Top 100列表,建议访问官方推荐页面获取最新更新的信息。 ```python # 示例代码:验证括号的有效性 def isValid(s: str) -> bool: stack = [] mapping = {")": "(", "}": "{", "]": "["} for char in s: if char in mapping.values(): stack.append(char) elif char in mapping.keys(): if not stack or stack.pop() != mapping[char]: return False return len(stack) == 0 ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值