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
}
相关推荐
@听风吟17 分钟前
力扣之182.查找重复的电子邮箱
大数据·javascript·数据库·sql·leetcode
拉玛干2 小时前
社团周报系统可行性研究-web后端框架对比-springboot,django,gin
数据库·python·spring·golang
Ddddddd_1582 小时前
C++ | Leetcode C++题解之第421题数组中两个数的最大异或值
c++·leetcode·题解
ly-how2 小时前
leetcode练习 二叉树的层序遍历
算法·leetcode
大二转专业3 小时前
408算法题leetcode--第10天
考研·算法·leetcode
shark-chili3 小时前
数据结构与算法-Trie树添加与搜索
java·数据结构·算法·leetcode
gopher95114 小时前
go语言 数组和切片
开发语言·golang
gopher95114 小时前
go语言Map详解
开发语言·golang
Python私教4 小时前
Go语言现代web开发15 Mutex 互斥锁
开发语言·前端·golang