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
}
相关推荐
GalaxyPokemon1 分钟前
LeetCode - 53. 最大子数组和
算法·leetcode·职场和发展
hn小菜鸡37 分钟前
LeetCode 1356.根据数字二进制下1的数目排序
数据结构·算法·leetcode
zhuiQiuMX41 分钟前
分享今天做的力扣SQL题
sql·算法·leetcode
roman_日积跬步-终至千里2 小时前
【Go语言基础【20】】Go的包与工程
开发语言·后端·golang
全栈凯哥3 小时前
Java详解LeetCode 热题 100(26):LeetCode 142. 环形链表 II(Linked List Cycle II)详解
java·算法·leetcode·链表
全栈凯哥4 小时前
Java详解LeetCode 热题 100(27):LeetCode 21. 合并两个有序链表(Merge Two Sorted Lists)详解
java·算法·leetcode·链表
SuperCandyXu4 小时前
leetcode2368. 受限条件下可到达节点的数目-medium
数据结构·c++·算法·leetcode
蒟蒻小袁5 小时前
力扣面试150题--被围绕的区域
leetcode·面试·深度优先
GalaxyPokemon6 小时前
LeetCode - 148. 排序链表
linux·算法·leetcode