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
}
相关推荐
Tisfy7 分钟前
LeetCode 2110.股票平滑下跌阶段的数目:数学(一次遍历)
数学·算法·leetcode·题解
2501_944875511 小时前
Go后端工程师
开发语言·后端·golang
理人综艺好会1 小时前
Redis学习之go-redis
redis·学习·golang
bing.shao1 小时前
Golang WaitGroup 踩坑
开发语言·数据库·golang
周杰伦_Jay2 小时前
【Go/Python/Java】基础语法+核心特性对比
java·python·golang
练习时长一年2 小时前
LeetCode热题100(搜索插入位置)
数据结构·算法·leetcode
(●—●)橘子……3 小时前
记力扣557.反转字符串中的单词 练习理解
算法·leetcode·职场和发展
serendipity_hky4 小时前
【go语言 | 第3篇】go中类的封装、继承、多态 + 反射
开发语言·后端·golang·反射
sprintzer4 小时前
12.06-12.15力扣分治法刷题
算法·leetcode
月明长歌4 小时前
【码道初阶】【牛客BM30】二叉搜索树与双向链表:java中以引用代指针操作的艺术与陷阱
java·数据结构·算法·leetcode·二叉树·笔试·字节跳动