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
}
相关推荐
Kuo-Teng6 小时前
Leetcode438. 找到字符串中所有字母异位词
java·算法·leetcode
赵文宇(温玉)7 小时前
构建内网离线的“github.com“,完美解决内网Go开发依赖
开发语言·golang·github
墨染点香7 小时前
LeetCode 刷题【138. 随机链表的复制】
算法·leetcode·链表
草明8 小时前
Go 的 IO 多路复用
开发语言·后端·golang
Shinom1ya_13 小时前
算法 day 41
数据结构·算法·leetcode
一匹电信狗14 小时前
【C++】红黑树详解(2w字详解)
服务器·c++·算法·leetcode·小程序·stl·visual studio
仰泳的熊猫16 小时前
LeetCode:72. 超级次方
数据结构·c++·算法·leetcode
_dindong17 小时前
牛客101:递归/回溯
数据结构·c++·笔记·学习·算法·leetcode·深度优先
刃神太酷啦17 小时前
力扣校招算法通关:双指针技巧全场景拆解 —— 从数组操作到环检测的高效解题范式
java·c语言·数据结构·c++·算法·leetcode·职场和发展
Shinom1ya_18 小时前
算法 day 42
数据结构·算法·leetcode