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
}
相关推荐
小欣加油41 分钟前
leetcode 143 重排链表
数据结构·c++·算法·leetcode·链表
猫梦www2 小时前
力扣21:合并两个有序链表
数据结构·算法·leetcode·链表·golang·力扣
爱coding的橙子2 小时前
每日算法刷题Day76:10.19:leetcode 二叉树12道题,用时3h
算法·leetcode·职场和发展
夏鹏今天学习了吗4 小时前
【LeetCode热题100(47/100)】路径总和 III
算法·leetcode·职场和发展
smj2302_796826524 小时前
解决leetcode第3721题最长平衡子数组II
python·算法·leetcode
m0_626535204 小时前
力扣题目练习 换水问题
python·算法·leetcode
一匹电信狗4 小时前
【LeetCode_160】相交链表
c语言·开发语言·数据结构·c++·算法·leetcode·stl
·白小白6 小时前
力扣(LeetCode) ——118.杨辉三角(C++)
c++·算法·leetcode
std78796 小时前
Rust 与 Go – 比较以及每个如何满足您的需求
开发语言·golang·rust
仰泳的熊猫7 小时前
LeetCode:207. 课程表
数据结构·c++·算法·leetcode