150强访谈简单

太平洋大西洋水流

“太平洋大西洋水流”问题的详细指南和 Python 实施。

问题陈述

简单

有一个 m x n 矩形岛屿,与太平洋和大西洋接壤。太平洋接触该岛的左侧和顶部边缘,大西洋接触该岛的右侧和底部边缘。

该岛被划分为方形网格。给定一个 m x n 整数矩阵高度,其中 heights[r][c] 表示坐标 (r, c) 处单元格的海拔高度。

如果相邻单元格的高度小于或等于当前单元格的高度,则雨水可以直接流向北、南、东、西的相邻单元格。水可以从与海洋相邻的任何细胞流入该海洋。

返回网格坐标结果的二维列表,其中 result[i] = [ri, ci] 表示雨水可以从单元格 (ri, ci) 流向太平洋和大西洋。

编写一个函数 pacificAtlantic(heights: List[List[int]]) -> List[List[int]]

约束条件
  • m == len(heights)
  • n == len(heights[0])
  • 1 <= m, n <= 200
  • 0 <= heights[i][j] <= 10^5

示例

Example 1
Input
heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
Output
[[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
Explanation

These coordinates can flow to both Pacific (via top/left) and Atlantic (via bottom/right) oceans.

Example 2
Input
heights = [[1]]
Output
[[0,0]]
Explanation

The single cell borders both oceans directly.

Need a Hint?
考虑使用特定于图的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。