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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。