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
}
相关推荐
52Hz11832 分钟前
力扣20.有效的括号、155.最小栈
python·算法·leetcode
菜鸡儿齐1 小时前
leetcode-电话号码的字母组合
算法·leetcode·职场和发展
We་ct2 小时前
LeetCode 236. 二叉树的最近公共祖先:两种解法详解(递归+迭代)
前端·数据结构·算法·leetcode·typescript
小白菜又菜2 小时前
Leetcode 229. Majority Element II
算法·leetcode·职场和发展
Frostnova丶2 小时前
LeetCode 1461. 检查一个字符串是否包含所有长度为 K 的二进制子串
算法·leetcode·哈希算法
历程里程碑2 小时前
普通数组---合并区间
java·大数据·数据结构·算法·leetcode·elasticsearch·搜索引擎
小白菜又菜3 小时前
Leetcode 236. Lowest Common Ancestor of a Binary Tree
python·算法·leetcode
不想看见4043 小时前
01 Matrix 基本动态规划:二维--力扣101算法题解笔记
c++·算法·leetcode
Navigator_Z4 小时前
LeetCode //C - 964. Least Operators to Express Number
c语言·算法·leetcode
骇城迷影4 小时前
代码随想录:二叉树篇(中)
数据结构·c++·算法·leetcode