Pacific Atlantic Water Flow
Detailed guide and Python implementation for the 'Pacific Atlantic Water Flow' problem.
1. Concept Overview
The 'Pacific Atlantic Water Flow' problem is a key challenge in the Graphs section.
This implementation focuses on easy-level logic in Python.
We prioritize technical accuracy and code readability in our provided solutions.
2. Real-World Applications
3. Visual Intuition
Visualizing the logic flow for Pacific Atlantic Water Flow.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Read the problem statement for Pacific Atlantic Water Flow carefully.
2. Formulate brute force
Draft a simple iterative solution.
3. Identify inefficiency
Look for redundant calculations.
4. Optimize search path
Use hashing or sorting to speed up the process.
5. Final Implementation
Clean up the code for production standards.
Problem Statement
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).
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 that 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.
Write a function 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
Examples
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]]
[[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
These coordinates can flow to both Pacific (via top/left) and Atlantic (via bottom/right) oceans.
heights = [[1]]
[[0,0]]
The single cell borders both oceans directly.
Need a Hint?
Edge Cases to Watch
- Empty input structures
- Single element inputs
- Large numerical bounds
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Interview Insights & Variations
Complexity Analysis Breakdown
Why Time: Directly evaluates all possibilities.
Why Space: Uses standard local memory.
Why Time: Optimized paths reduce total operations.
Why Space: May trade memory for speed.
Optimized Solution Python Code
Optimized Solution Python Code
def pacific_atlantic_opt(heights):
ROWS, COLS = len(heights), len(heights[0])
pac, atl = set(), set()
def dfs(r, c, visit, prevHeight):
if ((r, c) in visit or r < 0 or c < 0 or r == ROWS or c == COLS or heights[r][c] < prevHeight):
return
visit.add((r, c))
dfs(r + 1, c, visit, heights[r][c])
dfs(r - 1, c, visit, heights[r][c])
dfs(r, c + 1, visit, heights[r][c])
dfs(r, c - 1, visit, heights[r][c])
for c in range(COLS):
dfs(0, c, pac, heights[0][c])
dfs(ROWS - 1, c, atl, heights[ROWS - 1][c])
for r in range(ROWS):
dfs(r, 0, pac, heights[r][0])
dfs(r, COLS - 1, atl, heights[r][COLS - 1])
res = []
for r in range(ROWS):
for c in range(COLS):
if (r, c) in pac and (r, c) in atl:
res.append([r, c])
return resBrute Force Code (Spoiler Guarded)
Brute Force Code (Spoiler Guarded)
def pacific_atlantic_brute(heights):
res = []
ROWS, COLS = len(heights), len(heights[0])
def can_reach(r, c, target_set):
visited = set()
q = [(r, c)]
visited.add((r, c))
while q:
curr_r, curr_c = q.pop(0)
if (curr_r, curr_c) in target_set: return True
for dr, dc in [[1,0], [-1,0], [0,1], [0,-1]]:
nr, nc = curr_r + dr, curr_c + dc
if 0 <= nr < ROWS and 0 <= nc < COLS and (nr, nc) not in visited and heights[nr][nc] <= heights[curr_r][curr_c]:
visited.add((nr, nc))
q.append((nr, nc))
return False
pac_border = set([(0, c) for c in range(COLS)] + [(r, 0) for r in range(ROWS)])
atl_border = set([(ROWS-1, c) for c in range(COLS)] + [(r, COLS-1) for r in range(ROWS)])
for r in range(ROWS):
for c in range(COLS):
if can_reach(r, c, pac_border) and can_reach(r, c, atl_border):
res.append([r, c])
return resAlgorithm Pattern Checklist
When dealing with Graphs data patterns.
Core Prerequisites
Revision Key Notes
Common Mistakes & Pitfalls
Related Questions
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python Control Flow
Master conditional statements, loops, and loop control structures in Python. Learn if-else, for, while, break, and continue.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.