LeetCode - 417 - Pacific Atlantic Water Flow

24 篇文章 0 订阅

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

上边界和左边界为Pacific,下边界和右边界为Atlantic,所有的洋流只能朝着小于等于其值的方向流动,问哪些可以既可以流入Pacific又可以流入Atlantic。

一个dfs,设置两个visit表示点(i,j)是否可以流入哪个大洋。时间复杂度O(nm),空间复杂度O(nm)

class Solution {
public:
    vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) {
        vector<pair<int, int> > ans;
        if (!matrix.size() || !matrix[0].size()) return ans;
        int n = matrix.size(), m = matrix[0].size();
        
        vector<vector<bool> > pacific(n, vector<bool>(m, false));
        vector<vector<bool> > atlantic(n, vector<bool>(m, false));
        
        for (int i = 0; i < n; ++i) {
            dfs(matrix, pacific, i, 0, INT_MIN);
            dfs(matrix, atlantic, i, m-1, INT_MIN);
        }
        for (int i = 0; i < m; ++i) {
            dfs(matrix, pacific, 0, i, INT_MIN);
            dfs(matrix, atlantic, n-1, i, INT_MIN);
        }
        
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                if (pacific[i][j] && atlantic[i][j]) {
                    ans.push_back(make_pair(i, j));
                }
            }
        }
        return ans;
    }
private:
    int dir[4][2] = {1, 0, 0, 1, -1, 0, 0, -1};
    void dfs(vector<vector<int>>& matrix, vector<vector<bool> >& vis, int x, int y, int height) {
        int n = matrix.size(), m = matrix[0].size();
        if (x < 0 || y < 0 || x >= n || y >= m || matrix[x][y] < height) return;
        if (vis[x][y]) return;
        vis[x][y] = true;   
        for (int i = 0; i < 4; ++i) {
            dfs(matrix, vis, x + dir[i][0], y + dir[i][1], matrix[x][y]);
        }
        return;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值