Golang | Leetcode Golang题解之第417题太平洋大西洋水流问题

题目:

题解:

Go 复制代码
type pair struct{ x, y int }
var dirs = []pair{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}

func pacificAtlantic(heights [][]int) (ans [][]int) {
    m, n := len(heights), len(heights[0])
    pacific := make([][]bool, m)
    atlantic := make([][]bool, m)
    for i := range pacific {
        pacific[i] = make([]bool, n)
        atlantic[i] = make([]bool, n)
    }

    bfs := func(x, y int, ocean [][]bool) {
        if ocean[x][y] {
            return
        }
        ocean[x][y] = true
        q := []pair{{x, y}}
        for len(q) > 0 {
            p := q[0]
            q = q[1:]
            for _, d := range dirs {
                if x, y := p.x+d.x, p.y+d.y; 0 <= x && x < m && 0 <= y && y < n && !ocean[x][y] && heights[x][y] >= heights[p.x][p.y] {
                    ocean[x][y] = true
                    q = append(q, pair{x, y})
                }
            }
        }
    }
    for i := 0; i < m; i++ {
        bfs(i, 0, pacific)
    }
    for j := 1; j < n; j++ {
        bfs(0, j, pacific)
    }
    for i := 0; i < m; i++ {
        bfs(i, n-1, atlantic)
    }
    for j := 0; j < n-1; j++ {
        bfs(m-1, j, atlantic)
    }

    for i, row := range pacific {
        for j, ok := range row {
            if ok && atlantic[i][j] {
                ans = append(ans, []int{i, j})
            }
        }
    }
    return
}
相关推荐
无敌昊哥战神7 小时前
【LeetCode 257】二叉树的所有路径(回溯法/深度优先遍历)- Python/C/C++详细题解
c语言·c++·python·leetcode·深度优先
x_xbx8 小时前
LeetCode:148. 排序链表
算法·leetcode·链表
木井巳10 小时前
【递归算法】子集
java·算法·leetcode·决策树·深度优先
lightqjx10 小时前
【算法】二分算法
c++·算法·leetcode·二分算法·二分模板
灰色小旋风11 小时前
力扣21 合并两个有序链表(C++)
c++·leetcode·链表
王老师青少年编程12 小时前
2026年3月GESP真题及题解(C++五级):有限不循环小数
c++·题解·真题·gesp·csp·五级·有限不循环小数
JCGKS12 小时前
海量文档单词计数算法方案分析
golang·数据结构与算法·海量数据·搜索引起·倒排查找
老鼠只爱大米13 小时前
LeetCode经典算法面试题 #347:前 K 个高频元素(最小堆、桶排序、快速选择等多种实现方案详解)
算法·leetcode·堆排序·java面试题·桶排序·快速选择·topk
liuyao_xianhui13 小时前
优选算法_分治_快速排序_归并排序_C++
开发语言·数据结构·c++·算法·leetcode·排序算法·动态规划
福大大架构师每日一题15 小时前
ollama v0.18.2 发布!OpenClaw 安装优化、Claude 加速、MLX 量化全面升级
golang·ollama