Problem

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.

https://leetcode.com/problems/pacific-atlantic-water-flow/

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[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.length
  • n == heights[r].length
  • 1 <= m, n <= 200
  • 0 <= heights[r][c] <= 10^5

Test Cases

1
2
class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
solution_test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import pytest

from solution import Solution


@pytest.mark.parametrize('heights, expected', [
(
[[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]],
[[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
),
([[1]], [[0,0]]),

(
[
[19,16,16,12,14,0,17,11,2,0,18,9,13,16,8,8,8,13,17,9,16,9,4,7,1,19,10,7,0,15],
[0,11,4,14,9,0,6,13,16,5,19,9,4,5,4,12,0,13,0,7,9,12,13,15,3,7,4,9,15,1],
[13,14,12,12,12,16,6,15,13,1,8,9,11,14,14,10,19,11,10,0,5,18,4,12,7,13,17,15,18,1],
[16,14,19,5,8,2,11,17,7,1,4,6,5,18,7,15,6,19,18,12,1,14,2,2,0,9,15,14,13,19],
[17,4,12,9,12,10,12,10,4,5,12,7,2,12,18,10,10,8,6,1,5,13,10,3,5,3,11,4,8,11],
[8,19,18,9,6,2,7,3,19,6,0,17,9,12,11,1,15,11,18,1,8,11,1,11,16,7,8,17,15,0],
[7,0,5,11,1,7,12,18,12,1,5,2,11,7,18,12,0,11,9,18,5,2,3,1,1,1,8,14,19,5],
[2,14,2,16,17,19,10,16,1,16,16,3,19,12,13,17,19,12,16,10,16,8,16,12,6,12,13,17,9,12],
[8,1,10,5,7,0,15,19,8,15,4,12,18,18,13,11,5,2,8,3,15,4,3,7,7,14,15,11,6,16],
[0,5,13,19,1,1,2,4,16,2,16,9,15,15,10,10,18,11,17,1,5,14,5,19,7,0,13,7,13,7],
[11,6,16,12,4,2,9,11,17,19,12,10,6,16,17,5,1,18,19,7,15,1,14,0,3,19,7,3,4,13],
[4,11,8,10,10,19,7,18,4,2,2,14,6,9,18,14,2,16,5,3,19,17,4,3,7,1,12,2,4,3],
[14,16,3,11,13,13,6,16,18,0,17,19,4,1,14,12,4,17,5,19,8,13,15,3,15,4,1,14,12,10],
[13,2,12,2,16,12,19,10,19,12,19,14,12,17,16,3,13,7,3,15,16,7,10,15,14,10,6,5,2,18]
],
[[0,29],[1,28],[2,28],[12,0],[12,1],[13,0]]
)
])
class Test:
def test_solution(self, heights, expected):
sol = Solution()
result = sol.pacificAtlantic(heights)
result.sort()
expected.sort()
assert result == expected

Thoughts

构造一个有 m * n + 2 个节点的有向图(可能有环),前 m * n 个节点对应 island 的每个 cell,最后两个节点分别对应太平洋(PO)和大西洋(AO)。

图中的有向边,表示从终点对应的 cell 可以流到起点对应的 cell(或海洋)。因为比较稀疏,可以用邻接表的存储方式。

从太平洋对应的节点出发,遍历所有可达的 cells。可以用栈辅助做深度优先遍历。然后也找出从大西洋可达的所有 cells。二者的交集就是结果。

时间和空间复杂度都是 O(m * n)

Code

solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from typing import List


class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
m = len(heights)
n = len(heights[0])
po = m * n # Pacific Ocean
ao = po + 1 # Atlantic Ocean
adjacencies: list[list[int]] = [[] for _ in range(ao + 1)]

# Build the graph (using adjacency list).
idx = 0
for i, row in enumerate(heights):
for j, h in enumerate(row):
if i == 0 or j == 0:
adjacencies[po].append(idx)
if i == m - 1 or j == n - 1:
adjacencies[ao].append(idx)

if i > 0 and heights[i-1][j] <= h:
adjacencies[idx - n].append(idx)
if i < m - 1 and heights[i+1][j] <= h:
adjacencies[idx + n].append(idx)
if j > 0 and heights[i][j-1] <= h:
adjacencies[idx - 1].append(idx)
if j < n - 1 and heights[i][j+1] <= h:
adjacencies[idx + 1].append(idx)

idx += 1

# Find Pacific Ocean and Atlantic Ocean's reachable vertices.
po_cells = self._traverse_reachable(adjacencies, po)
ao_cells = self._traverse_reachable(adjacencies, ao)

# Calc the intersect of the two oceans' reachable vertices, in 2d coordinate format.
return [[*divmod(v, n)] for v in po_cells & ao_cells]

def _traverse_reachable(self, adjacencies: list[list[int]], root: int) -> set[int]:
reachable = set()
stack = [root]
while stack:
vertex = stack.pop()
neighbors = [v for v in adjacencies[vertex] if v not in reachable]
stack.extend(neighbors)
reachable.update(neighbors)

return reachable