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

【力扣:417】太平洋大西洋水流问题_第1张图片

【力扣:417】太平洋大西洋水流问题_第2张图片
模拟沿岸找高点,找到向内走直到向内无路可走(当前位置高于内部位置),当从相对两边都能走到当前位置,那么当前位置的水可以流向两边。

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;
    }
};

你可能感兴趣的:(leetcode,算法,c++)