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
}
相关推荐
轮到我狗叫了1 小时前
力扣310.最小高度树(拓扑排序,无向图),力扣.加油站力扣.矩阵置零力扣.二叉树中的最大路径和
算法·leetcode·职场和发展
爱coding的橙子1 小时前
算法刷题Day9 5.18:leetcode定长滑动窗口3道题,结束定长滑动窗口,用时1h
算法·leetcode·职场和发展
小刘不想改BUG2 小时前
LeetCode LCR 010 和为 K 的子数组 (Java)
java·算法·leetcode
{⌐■_■}3 小时前
【kafka】kafka概念,使用技巧go示例
golang·kafka·linq
小雅痞4 小时前
[Java][Leetcode middle] 12. 整数转罗马数字
java·linux·leetcode
Espresso Macchiato4 小时前
Leetcode 3551. Minimum Swaps to Sort by Digit Sum
leetcode·排序·leetcode medium·leetcode 3551·leetcode周赛450
Villiam_AY4 小时前
Go 后端中双 token 的实现模板
开发语言·后端·golang
緈福的街口15 小时前
【leetcode】2900. 最长相邻不相等子序列 I
算法·leetcode·职场和发展
进击的小白菜16 小时前
LeetCode 153. 寻找旋转排序数组中的最小值:二分查找法详解及高频疑问解析
数据结构·算法·leetcode
Chandler2418 小时前
Go语言 GORM框架 使用指南
开发语言·后端·golang·orm