【力扣:417】太平洋大西洋水流问题

在这里插入图片描述

在这里插入图片描述
模拟沿岸找高点,找到向内走直到向内无路可走(当前位置高于内部位置),当从相对两边都能走到当前位置,那么当前位置的水可以流向两边。

class Solution {
private:
    void dfs(vector<vector<int>> &heights, vector<vector<int>> &count, int &row,
     int &col, int x, int y, int height, int mask) {
        if (x < 0 || y < 0 || x >= row || y >= col || 
        heights[x][y] < height || count[x][y] & mask) return;
        count[x][y] |= mask;
        dfs(heights, count, row, col, x - 1, y, heights[x][y], mask);
        dfs(heights, count, row, col, x + 1, y, heights[x][y], mask);
        dfs(heights, count, row, col, x, y - 1, heights[x][y], mask);
        dfs(heights, count, row, col, x, y + 1, heights[x][y], mask);
    }
public:
    vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
        int row = heights.size(), col = heights[0].size();
        vector<vector<int>> ans;
        vector<vector<int>> count(row, vector<int>(col, 0));
        for (int r = 0; r < row; ++r) {
            dfs(heights, count, row, col, r, 0, 0, 0x0f);
            dfs(heights, count, row, col, r, col - 1, 0, 0xf0);
        }
        for (int c = 0; c < col; ++c) {
            dfs(heights, count, row, col, 0, c, 0, 0x0f);
            dfs(heights, count, row, col, row - 1, c, 0, 0xf0);
        }
        for (int r = 0; r < row; ++r) {
            for (int c = 0; c < col; ++c) {
                if (count[r][c] == 0xff) ans.push_back(vector<int> {r, c});
            }
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值