LeetCode 417 太平洋大西洋水流问题[DFS] HERODING的LeetCode之路

在这里插入图片描述
在这里插入图片描述

解题思路:
这是一道经典DFS变形问题,需要两遍DFS,第一遍是为了找到通往大西洋的雨水连通图,第二遍是寻找通往太平洋的雨水连通图,最后对比两个连通图的连通状态,把都连通的点找出,代码如下:

class Solution {
private:
int m, n;
    int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public:
    vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
        vector<vector<int>> ans;
        m = heights.size(), n = heights[0].size();
        vector<vector<bool>> visitPacific(m, vector<bool>(n, false));
        vector<vector<bool>> visitAtlantic(m, vector<bool>(n, false));
        // 遍历左界和右界
        for(int i = 0; i < m; i ++) {
            dfs(heights, visitPacific, i, 0);
            dfs(heights, visitAtlantic, i, n - 1);
        }
        // 遍历上界和下界
        for(int j = 0; j < n; j ++) {
            dfs(heights, visitPacific, 0, j);
            dfs(heights, visitAtlantic, m - 1, j);
        }
        for(int i = 0; i < m; i ++) {
            for(int j = 0; j < n; j ++) {
                if(visitAtlantic[i][j] && visitPacific[i][j]) {
                    ans.push_back({i, j});
                }
            }
        }
        return ans;
    }    

    void dfs(vector<vector<int>>& heights, vector<vector<bool>>& visited, int x, int y) {
        visited[x][y] = true;
        for(int i = 0 ; i < 4; i ++) {
            int nextx = x + dir[i][0];
            int nexty = y + dir[i][1];
            // 不越界且未访问过
            if(nextx >= 0 && nextx < m && nexty >= 0 && nexty < n && !visited[nextx][nexty]) {
                // 满足水流条件
                if(heights[nextx][nexty] >= heights[x][y]) {
                    dfs(heights, visited, nextx, nexty);
                }
            }
        }
        return;
    }
};
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HERODING77

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值