欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > Golang | Leetcode Golang题解之第417题太平洋大西洋水流问题

Golang | Leetcode Golang题解之第417题太平洋大西洋水流问题

2025/3/10 6:18:33 来源:https://blog.csdn.net/weixin_66442839/article/details/142373371  浏览:    关键词:Golang | Leetcode Golang题解之第417题太平洋大西洋水流问题

题目:

题解:

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] = trueq := []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] = trueq = 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
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词