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
}
相关推荐
运筹vivo@1 天前
2657. 找到两个数组的前缀公共数组 | 难度:中等
算法·leetcode·职场和发展·哈希表
比特森林探险记1 天前
go 语言中的context 解读和用法
开发语言·后端·golang
叶小鸡1 天前
小鸡玩算法-力扣HOT100-动态规划(下)
算法·leetcode·动态规划
毅炼1 天前
今日LeetCode 摸鱼打卡
java·算法·leetcode
m0_629494731 天前
LeetCode 热题 100-----28. 两数相加
数据结构·算法·leetcode·链表
菜菜的顾清寒1 天前
力扣HOT100(25)环形链表
算法·leetcode·链表
jieyucx2 天前
从基础语法到面向对象:Go语言如何实现封装、继承与多态?
开发语言·后端·golang
littleschemer2 天前
Go:实现游戏服务器网关
服务器·网关·游戏·golang
Controller-Inversion2 天前
76. 最小覆盖子串
java·算法·leetcode
_日拱一卒2 天前
LeetCode:437路径总和Ⅲ
算法·leetcode·职场和发展