java 力扣 417.太平洋大西洋水流问题

1.题目

2.解法

①二维数组+dfs

class Solution {
    private int[][] directions = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
    private int row, col;

    public List<List<Integer>> pacificAtlantic(int[][] heights) {
        if(heights.length == 0 || heights[0].length == 0) return new ArrayList<>();

        List<List<Integer>> res = new ArrayList<>();
        row = heights.length;
        col = heights[0].length;
        boolean[][] tai = new boolean[row][col];
        boolean[][] big = new boolean[row][col];

        for(int i = 0; i < row; i++){
            dfs(i, 0, heights, tai);
            dfs(i, col - 1, heights, big);
        }
        for(int j = 0; j < col; j++){
            dfs(0, j, heights, tai);
            dfs(row - 1, j, heights, big);
        }

        for(int i = 0; i < row; i++){
            for(int j = 0; j < col; j++){
                if(tai[i][j] && big[i][j]) res.add(Arrays.asList(i, j));
            }
        }
        return res;
    }

    private void dfs(int r, int c, int[][] heights, boolean[][] canReach){
        if(canReach[r][c]) return;

        canReach[r][c] = true;
        for(int[] d : directions){
            int nextR = r + d[0];
            int nextC = c + d[1];
            if(nextR < 0 || nextR >= row || nextC < 0 || nextC >= col || heights[nextR][nextC] < heights[r][c]){
                continue;
            }
            dfs(nextR, nextC, heights, canReach);
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值