LeetCode #417 - Pacific Atlantic Water Flow

本文探讨了一种算法,用于确定二维矩阵中的哪些位置可以让水流同时到达太平洋和大西洋。通过从边界开始进行递归搜索,标记所有可达的网格单元,最终找出那些能够流向两个方向的特殊坐标。

摘要生成于 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:

  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).

矩阵的左边界和上边界是太平洋,右边就和下边界是大西洋,矩阵中每个元素的值代表坐标对应的高度,求哪些坐标的的水可以同时流到太平洋和大西洋。可以从矩阵的边界出发,利用递归搜索可以遍历到的所有节点,就代表哪些坐标的水可以流到太平洋或大西洋。

class Solution {
public:
    vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) {
        vector<pair<int,int>> result;
        if(matrix.size()==0||matrix[0].size()==0) return result;
        int m=matrix.size();
        int n=matrix[0].size();
        vector<vector<bool>> P(m,vector<bool>(n,false));
        vector<vector<bool>> A(m,vector<bool>(n,false));
        
        for(int i=0;i<m;i++)
        {
            search_surround(i,0,P,matrix);
            search_surround(i,n-1,A,matrix);
        }
        for(int j=0;j<n;j++)
        {
            search_surround(0,j,P,matrix);
            search_surround(m-1,j,A,matrix);
        }
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
                if(P[i][j]==true&&A[i][j]==true) 
                    result.push_back(pair<int,int>(i,j));

        return result;
    }
    
    void search_surround(int i, int j, vector<vector<bool>>& X, vector<vector<int>> matrix)
    {
        if(X[i][j]==true) return;
        X[i][j]=true;
        if(i-1>=0&&matrix[i][j]<=matrix[i-1][j]) search_surround(i-1,j,X,matrix);
        if(i+1<X.size()&&matrix[i][j]<=matrix[i+1][j]) search_surround(i+1,j,X,matrix);
        if(j-1>=0&&matrix[i][j]<=matrix[i][j-1])search_surround(i,j-1,X,matrix);
        if(j+1<X[0].size()&&matrix[i][j]<=matrix[i][j+1])search_surround(i,j+1,X,matrix);
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值