本文完整拆解 LeetCode 417 Pacific Atlantic Water Flow 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Pacific Atlantic Water Flow 一次弄懂。
Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link
There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island’s left and top edges, and the Atlantic Ocean touches the island’s right and bottom edges.
The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c).
The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell’s height is less than or equal to the current cell’s height. Water can flow from any cell adjacent to an ocean into the ocean.
Return a 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water can flow from cell (ri, ci) to both the Pacific and Atlantic oceans.
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: The following cells can flow to the Pacific and Atlantic oceans, as shown below:
[0,4]: [0,4] -> Pacific Ocean
[0,4] -> Atlantic Ocean
[1,3]: [1,3] -> [0,3] -> Pacific Ocean
[1,3] -> [1,4] -> Atlantic Ocean
[1,4]: [1,4] -> [1,3] -> [0,3] -> Pacific Ocean
[1,4] -> Atlantic Ocean
[2,2]: [2,2] -> [1,2] -> [0,2] -> Pacific Ocean
[2,2] -> [2,3] -> [2,4] -> Atlantic Ocean
[3,0]: [3,0] -> Pacific Ocean
[3,0] -> [4,0] -> Atlantic Ocean
[3,1]: [3,1] -> [3,0] -> Pacific Ocean
[3,1] -> [4,1] -> Atlantic Ocean
[4,0]: [4,0] -> Pacific Ocean
[4,0] -> Atlantic Ocean
Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans.
Example 2:
Input: heights = [[1]] Output: [[0,0]] Explanation: The water can flow from the only cell to the Pacific and Atlantic oceans.
Constraints:
m == heights.lengthn == heights[r].length1 <= m, n <= 2000 <= heights[r][c] <= 105
Python
# time complexity: O(m*n)
# space complexity: O(m*n)
from collections import deque
from typing import List
class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
ROW = len(heights)
COL = len(heights[0])
if not ROW or not COL:
return []
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
pacificQueue = deque()
atlanticQueue = deque()
for i in range(ROW):
pacificQueue.append((i, 0))
atlanticQueue.append((i, COL - 1))
for i in range(COL):
pacificQueue.append((0, i))
atlanticQueue.append((ROW - 1, i))
def bfs(queue):
reachable = set()
while queue:
currX, currY = queue.popleft()
reachable.add((currX, currY))
for (dX, dY) in directions:
nextX = currX + dX
nextY = currY + dY
if nextX < 0 or nextX >= ROW or nextY < 0 or nextY >= COL:
continue
if (nextX, nextY) in reachable:
continue
if heights[currX][currY] > heights[nextX][nextY]:
continue
queue.append((nextX, nextY))
return reachable
pacificSet = bfs(pacificQueue)
atlanticSet = bfs(atlanticQueue)
return list(pacificSet.intersection(atlanticSet))
heights = [[1, 1], [1, 1], [1, 1]]
print(Solution().pacificAtlantic(heights))
Pacific Atlantic Water Flow 解題思路
正向思考(從每格往外流)會重複計算大量路徑。反向思考才是關鍵:從海洋邊界往內陸「逆流而上」,只走到高度大於等於目前格子的鄰居。分別從太平洋與大西洋邊界各跑一次搜尋,兩個可達集合的交集就是答案。
Pacific Atlantic Water Flow 演算法步驟
- 建立兩個布林矩陣 pacific 與 atlantic。
- 從上邊界與左邊界的所有格子出發做 DFS,標記 pacific 可達。
- 從下邊界與右邊界的所有格子出發做 DFS,標記 atlantic 可達。
- DFS 時只往「高度大於等於目前格子」的鄰居走;最後收集兩個矩陣皆為 true 的座標。
Pacific Atlantic Water Flow 複雜度分析
| 項目 | 複雜度 |
|---|---|
| 時間複雜度 | O(m·n) |
| 空間複雜度 | O(m·n) |
每個格子在兩次搜尋中各最多被走訪一次,時間為 O(m·n)。兩個布林矩陣與遞迴堆疊都是 O(m·n)。反向搜尋把原本可能的指數級路徑壓成線性。
Pacific Atlantic Water Flow 的邊界情況與常見錯誤
- 逆流的條件是「鄰居高度 >= 目前高度」,方向別寫反。
- 角落格子同時屬於兩個海洋的邊界,要在兩次搜尋中都當起點。
- 高度相同的相鄰格子可以互相流動,條件要用大於等於。
- 空矩陣直接回傳空陣列。
Pacific Atlantic Water Flow 其他解法比較
| 解法 | 時間 | 空間 | 說明 |
|---|---|---|---|
| 對每格正向 DFS 檢查能否到兩洋 | O((m·n)²) | O(m·n) | 重複計算嚴重 |
| BFS 從邊界逆流 | O(m·n) | O(m·n) | 與 DFS 等價 |
| 雙向逆流 DFS 取交集 | O(m·n) | O(m·n) | 本文採用 |

