417-Pacific Atlantic Water Flow

本文探讨了如何在一个表示大陆高度的矩阵中找到那些位置,从这些位置出发水流可以同时到达太平洋和大西洋。通过使用BFS和DFS两种方法,文章详细介绍了如何标记并遍历这些位置。

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

Description

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:

  1. The order of returned grid coordinates does not matter.
  2. 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).

问题描述

给定m * n 矩阵, 其元素为非负整数, 代表一块大陆上的每个单位方块的高度, 太平洋与矩阵的左边和上边相邻, 大西洋与矩阵的右边和下边相邻。

水流可以沿四个方向由一个方块(假设为A)流向另一个方块(假设为B), 若A的高度大于等于B的高度

返回那些水流既可以流入太平洋又可以流入大西洋的方块。

注意

  1. 返回的方块顺序不做要求
  2. m和n都小于150

问题分析

用BFS或者DFS做都可以, 关键是以四条边上的点作为起点往回推, 看哪些点可以流入太平洋或者大西洋


解法1(BFS)

public class Solution {
    int[][]dir = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

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

        int n = matrix.length, m = matrix[0].length;
        //One visited map for each ocean
        boolean[][] pacific = new boolean[n][m];
        boolean[][] atlantic = new boolean[n][m];
        Queue<int[]> pQueue = new LinkedList();
        Queue<int[]> aQueue = new LinkedList();

        for(int i = 0; i < n; i++){ //Vertical border
            pQueue.offer(new int[]{i, 0});
            aQueue.offer(new int[]{i, m - 1});
            pacific[i][0] = true;
            atlantic[i][m - 1] = true;
        }
        for(int i = 0; i < m; i++){ //Horizontal border
            pQueue.offer(new int[]{0, i});
            aQueue.offer(new int[]{n - 1, i});
            pacific[0][i] = true;
            atlantic[n - 1][i] = true;
        }

        bfs(matrix, pQueue, pacific);
        bfs(matrix, aQueue, atlantic);
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                if(pacific[i][j] && atlantic[i][j]){
                    res.add(new int[]{i, j});
                }
            }
        }

        return res;
    }
    public void bfs(int[][]matrix, Queue<int[]> queue, boolean[][]visited){
        int n = matrix.length, m = matrix[0].length;

        while(!queue.isEmpty()){
            int[] cur = queue.poll();
            for(int[] d : dir){
                int x = cur[0] + d[0];
                int y = cur[1] + d[1];
                if(x < 0 || x >= n || y < 0 || y >= m || visited[x][y] || matrix[x][y] < matrix[cur[0]][cur[1]])    continue;
                visited[x][y] = true;
                queue.offer(new int[]{x, y});
            } 
        }
    }
}

解法2

class Solution {
    private static final int VISITEDBYBOTH = 2;

    public List<int[]> pacificAtlantic(int[][] matrix) {
        //DFS from Ocean, which is four boundary.
        //Use one visited matrix: if visited by pacific : 1; if visited by atlantic: -1; if both: 2.
        //Time: O(MN) we only visited each cell twice. once from each ocsean. 
        //Space: O(MN) visited matrix.
        List<int[]> res = new LinkedList();
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0)   return res;

        int m = matrix.length;
        int n = matrix[0].length;
        int[][] visited = new int[m][n];
        int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

        for(int i = 0; i < m; i++){
            dfs(matrix, m, n, res, visited, i, 0, Integer.MIN_VALUE, 1, dirs);
            dfs(matrix, m, n, res, visited, i, n - 1, Integer.MIN_VALUE, -1, dirs);
        }
        for(int j = 0; j < n; j++){
            dfs(matrix, m, n, res, visited, 0, j, Integer.MIN_VALUE, 1, dirs);
            dfs(matrix, m, n, res, visited, m - 1, j, Integer.MIN_VALUE, -1, dirs);
        }

        return res;
    }
    private void dfs(int[][]matrix, int m, int n, List<int[]> res, int[][] visited, int i, int j, int minLimit, int curr, int[][] dirs){
        if(i < 0 || i >= m || j < 0 || j >= n || visited[i][j] == curr || visited[i][j] == VISITEDBYBOTH || matrix[i][j] < minLimit){
            return;
        } 

        if(visited[i][j] == -curr){
            visited[i][j] = VISITEDBYBOTH;
            res.add(new int[] {i, j});
        }else{
            visited[i][j] = curr;
        }   

        for(int[]dir : dirs)    dfs(matrix, m, n, res, visited, i + dir[0], j + dir[1], matrix[i][j], curr, dirs);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值