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
}
相关推荐
一只_程序媛1 小时前
【leetcode hot 100 42】接雨水
java·算法·leetcode
朔北之忘 Clancy2 小时前
2022 年 12 月青少年软编等考 C 语言五级真题解析
c语言·开发语言·c++·学习·算法·青少年编程·题解
嵌入式码喽2 小时前
LeetCode 热门100题-搜索二维矩阵 II
算法·leetcode·矩阵
XYLoveBarbecue2 小时前
C++ 二叉树的前序遍历 - 力扣(LeetCode)
c++·leetcode
LuckyLay4 小时前
Golang学习笔记_40——模版方法模式
笔记·学习·设计模式·golang·模板方法模式
嵌入式码喽5 小时前
LeetCode 热门100题-螺旋矩阵
算法·leetcode·矩阵
_不会dp不改名_5 小时前
leetcode_34 在排序数组中查找元素的第一个和最后一个位置
算法·leetcode·职场和发展
01_6 小时前
力扣hot100——前k个高频元素 (优先队列法,相关总结文章见另一博客)
算法·leetcode·优先队列
清羽_ls7 小时前
leetcode 912. 排序数组
数据结构·算法·leetcode
Good Note7 小时前
Golang——常用库context和runtime
开发语言·爬虫·golang