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
}
相关推荐
帅那个帅2 小时前
go的雪花算法代码分享
开发语言·后端·golang
X在敲AI代码3 小时前
【无标题】
算法·leetcode·职场和发展
月明长歌3 小时前
【码道初阶】Leetcode136:只出现一次的数字:异或一把梭 vs HashMap 计数(两种解法完整复盘)
java·数据结构·算法·leetcode·哈希算法
IT艺术家-rookie3 小时前
golang--测试
golang
Swift社区3 小时前
LeetCode 456 - 132 模式
java·算法·leetcode
LYFlied3 小时前
【每日算法】LeetCode 152. 乘积最大子数组(动态规划)
前端·算法·leetcode·动态规划
圣保罗的大教堂3 小时前
leetcode 3075. 幸福值最大化的选择方案 中等
leetcode
linksinke4 小时前
在windows系统上搭建Golang多版本管理器(g)的配置环境
开发语言·windows·golang
Dream it possible!4 小时前
LeetCode 面试经典 150_回溯_单词搜索(104_79_C++_中等)
c++·leetcode·面试·回溯
2401_841495644 小时前
【LeetCode刷题】杨辉三角
数据结构·python·算法·leetcode·杨辉三角·时间复杂度·空间复杂度