Learn DSA
Depth-First Search
Greedy Algorithms
Pacific Atlantic Water Flow
DESCRIPTION (credit Leetcode.com)
You are given an m x n matrix of non-negative integers representing a grid of land. Each value in the grid represents the height of that piece of land.
The Pacific Ocean touches the left and top edges of the matrix, while the Atlantic Ocean touches the right and bottom edges. Water can only flow from a cell to its neighboring cells directly north, south, east, or west, but only if the height of the neighboring cell is equal to or lower than the current cell.
Write a function to return a list of grid coordinates (i, j) where water can flow to both the Pacific and Atlantic Oceans. Water can flow from all cells directly adjacent to the ocean into that ocean.
Example 1:
Input:
Output:
💻 Desktop Required
The code editor works best on larger screens. Please open this page on your computer to write and run code.
You are given an `m x n` matrix of non-negative integers representing a grid of land. Each value in the grid represents the height of that piece of land. The Pacific Ocean touches the left and top edges of the matrix, while the Atlantic Ocean touches the right and bottom edges. Water can only flow from a cell to its neighboring cells directly north, south, east, or west, but only if the height of the neighboring cell is equal to or lower than the current cell. <svg viewBox="73.0594 61.469 363.2979 356.772" width="100%" className="mt-8 mx-auto block" height="356.772" xmlns="http://www.w3.org/2000/svg" xmlns:bx="https://boxy-svg.com"> <g transform="matrix(1, 0, 0, 1, -94.13539123535155, 96.70106506347656)"> <g> <g opacity="1"> <rect rx="2" strokeWidth="5.833" stroke="#299a8d" className="box" fill="#59b9b0" height="70" width="70" opacity="0.85" strokeOpacity="0.85" x="210" y="0"/> <text className="values" fill="white" fontWeight="700" fontSize="35" textAnchor="middle" dominantBaseline="middle" x="245" y="35" style={{whiteSpace: 'pre'}}>1</text> </g> <g opacity="1"> <rect rx="2" strokeWidth="5.833" stroke="#299a8d" className="box" fill="#59b9b0" height="70" width="70" opacity="0.85" strokeOpacity="0.85" x="280" y="0"/> <text className="values" fill="white" fontWeight="700" fontSize="35" textAnchor="middle" dominantBaseline="middle" x="315" y="35" style={{whiteSpace: 'pre'}}>2</text> </g> <g opacity="1"> <rect rx="2" strokeWidth="5.833" stroke="#299a8d" className="box" fill="#59b9b0" height="70" width="70" opacity="0.85" strokeOpacity="0.85" x="350" y="0"/> <text className="values" fill="white" fontWeight="700" fontSize="35" textAnchor="middle" dominantBaseline="middle" x="385" y="35" style={{whiteSpace: 'pre'}}>2</text> </g> <g opacity="1"> <rect rx="2" strokeWidth="5.833" stroke="#299a8d" className="box" fill="#59b9b0" height="70" width="70" opacity="0.85" strokeOpacity="0.85" x="420" y="0"/> <text className="values" fill="white" fontWeight="700" fontSize="35" textAnchor="middle" dominantBaseline="middle" x="455" y="35" style={{whiteSpace: 'pre'}}>3</text> </g> <g opacity="1"> <rect rx="2" strokeWidth="5.833" stroke="#299a8d" className="box" fill="#59b9b0" height="70" width="70" opacity="0.85" strokeOpacity="0.85" x="210" y="70"/> <text className="values" fill="white" fontWeight="700" fontSize="35" textAnchor="middle" dominantBaseline="middle" x="245" y="105" style={{whiteSpace: 'pre'}}>3</text> </g> <g opacity="1"> <rect rx="2" strokeWidth="5.833" stroke="#299a8d" className="box" fill="#59b9b0" height="70" width="70" opacity="0.85" strokeOpacity="0.85" x="280" y="70"/> <text className="values" fill="white" fontWeight="700" fontSize="35" textAnchor="middle" dominantBaseline="middle" x="315" y="105" style={{whiteSpace: 'pre'}}>2</text> </g> <g opacity="1"> <rect rx="2" strokeWidth="5.833" stroke="#299a8d" className="box" fill="#59b9b0" height="70" width="70" opacity="0.85" strokeOpacity="0.85" x="350" y="70"/> <text className="values" fill="white" fontWeight="700" fontSize="35" textAnchor="middle" dominantBaseline="middle" x="385" y="105" style={{whiteSpace: 'pre'}}>3</text> </g> <g opacity="1"> <rect rx="2" strokeWidth="5.833" stroke="#299a8d" className="box" fill="#59b9b0" height="70" width="70" opacity="0.85" strokeOpacity="0.85" x="420" y="70"/> <text className="values" fill="white" fontWeight="700" fontSize="35" textAnchor="middle" dominantBaseline="middle" x="455" y="105" style={{whiteSpace: 'pre'}}>4</text> </g> <g opacity="1"> <rect rx="2" strokeWidth="5.833" stroke="#299a8d" className="box" fill="#59b9b0" height="70" width="70" opacity="0.85" strokeOpacity="0.85" x="210" y="140"/> <text className="values" fill="white" fontWeight="700" fontSize="35" textAnchor="middle" dominantBaseline="middle" x="245" y="175" style={{whiteSpace: 'pre'}}>3</text> </g> <g opacity="1"> <rect rx="2" strokeWidth="5.833" stroke="#299a8d" className="box" fill="#59b9b0" height="70" width="70" opacity="0.85" strokeOpacity="0.85" x="280" y="140"/> <text className="values" fill="white" fontWeight="700" fontSize="35" textAnchor="middle" dominantBaseline="middle" x="315" y="175" style={{whiteSpace: 'pre'}}>2</text> </g> <g opacity="1"> <rect rx="2" strokeWidth="5.833" stroke="#299a8d" className="box" fill="#59b9b0" height="70" width="70" opacity="0.85" strokeOpacity="0.85" x="350" y="140"/> <text className="values" fill="white" fontWeight="700" fontSize="35" textAnchor="middle" dominantBaseline="middle" x="385" y="175" style={{whiteSpace: 'pre'}}>4</text> </g> <g opacity="1"> <rect rx="2" strokeWidth="5.833" stroke="#299a8d" className="box" fill="#59b9b0" height="70" width="70" opacity="0.85" strokeOpacity="0.85" x="420" y="140"/> <text className="values" fill="white" fontWeight="700" fontSize="35" textAnchor="middle" dominantBaseline="middle" x="455" y="175" style={{whiteSpace: 'pre'}}>5</text> </g> <g opacity="1"> <rect rx="2" strokeWidth="5.833" stroke="#299a8d" className="box" fill="#59b9b0" height="70" width="70" opacity="0.85" strokeOpacity="0.85" x="210" y="210"/> <text className="values" fill="white" fontWeight="700" fontSize="35" textAnchor="middle" dominantBaseline="middle" x="245" y="245" style={{whiteSpace: 'pre'}}>3</text> </g> <g opacity="1"> <rect rx="2" strokeWidth="5.833" stroke="#299a8d" className="box" fill="#59b9b0" height="70" width="70" opacity="0.85" strokeOpacity="0.85" x="280" y="210"/> <text className="values" fill="white" fontWeight="700" fontSize="35" textAnchor="middle" dominantBaseline="middle" x="315" y="245" style={{whiteSpace: 'pre'}}>2</text> </g> <g opacity="1"> <rect rx="2" strokeWidth="5.833" stroke="#299a8d" className="box" fill="#59b9b0" height="70" width="70" opacity="0.85" strokeOpacity="0.85" x="350" y="210"/> <text className="values" fill="white" fontWeight="700" fontSize="35" textAnchor="middle" dominantBaseline="middle" x="385" y="245" style={{whiteSpace: 'pre'}}>4</text> </g> <g opacity="1"> <rect rx="2" strokeWidth="5.833" stroke="#299a8d" className="box" fill="#59b9b0" height="70" width="70" opacity="0.85" strokeOpacity="0.85" x="420" y="210"/> <text className="values" fill="white" fontWeight="700" fontSize="35" textAnchor="middle" dominantBaseline="middle" x="455" y="245" style={{whiteSpace: 'pre'}}>5</text> </g> </g> </g> <text style={{fill: 'rgb(51, 51, 51)', fontFamily: 'Avenir', fontSize: '20px', whiteSpace: 'pre', transformOrigin: '254.801px 74.8335px'}} transform="matrix(0, -1, 1, 0, -165.992065429687, 152.83332824707)" x="213.572" y="79.084">Pacific</text> <text style={{fill: 'rgb(51, 51, 51)', fontFamily: 'Avenir', fontSize: '20px', whiteSpace: 'pre', transformOrigin: '258.294px 412.029px'}} transform="matrix(0, 1, -1, 0, 158.807891845703, -159.12727355957)" x="210.885" y="412.773">Atlantic</text> <text style={{fill: 'rgb(51, 51, 51)', fontFamily: 'Avenir', fontSize: '20px', whiteSpace: 'pre'}} x="218.69" y="81.469">Pacific</text> <text style={{fill: 'rgb(51, 51, 51)', fontFamily: 'Avenir', fontSize: '20px', whiteSpace: 'pre'}} x="223.138" y="410.741">Atlantic</text> <path d="M 538.636 331.931 H 637.825 L 637.825 324.431 L 674.819 336.931 L 637.825 349.431 L 637.825 341.931 H 538.636 V 331.931 Z" style={{fill: 'rgb(216, 216, 216)', fillOpacity: 0, transformOrigin: '606.727px 336.931px'}} transform="matrix(-1, -0.000005000002, 0.000005000002, -1, -431.241845617863, -232.948559761464)" bx:shape="arrow 538.636 324.431 136.183 25 10 36.994 0 1@767b8330"/> <rect x="233.482" y="99.068" width="9.989" height="236.736" style={{fill: 'rgb(216, 216, 216)', fillOpacity: 0}}/> <rect x="234.007" y="327.364" width="45.057" height="11.538" style={{fill: 'rgb(216, 216, 216)', fillOpacity: 0}}/> <path d="M 291.827 314.783 H 306.919 L 306.919 307.283 L 326.919 319.783 L 306.919 332.283 L 306.919 324.783 H 291.827 V 314.783 Z" style={{fill: 'rgb(150, 206, 242)'}} transform="matrix(0.01098800078034401, -0.9999399781227112, 0.9999399781227112, 0.01098800078034401, -31.143688201904297, 608.0787353515624)" bx:shape="arrow 291.827 307.283 35.092 25 10 20 0 1@d76a824a"/> <path d="M 278.106 329.74 H 297.281 L 297.281 322.24 L 317.281 334.74 L 297.281 347.24 L 297.281 339.74 H 278.106 V 329.74 Z" style={{fill: 'rgb(150, 206, 242)'}} transform="matrix(-0.9999569654464722, -0.009235999546945095, 0.009235999546945095, -0.9999569654464722, 548.4841918945312, 675.3465576171874)" bx:shape="arrow 278.106 322.24 39.175 25 10 20 0 1@c48f0c9f"/> </svg> <figcaption className="text-sm text-center mb-8 text-gray-400">Water can flow from grid[3][2] to the neighboring cells with a lower height.</figcaption> Write a function to return a list of grid coordinates `(i, j)` where water can flow to both the Pacific and Atlantic Oceans. Water can flow from all cells directly adjacent to the ocean into that ocean.
Run your code to see results here
Have suggestions or found something wrong?
Explanation
Approach 1: Brute Force Approach
class Solution:def pacificAtlantic(self, matrix):if not matrix or not matrix[0]:return []rows, cols = len(matrix), len(matrix[0])pacific = set()atlantic = set()# Try to find a path from r, c to the Pacific or Atlantic ocean# via neighboring cells with lower heightsdef dfs(start_r, start_c, r, c, visited):if (r, c) in visited:returnvisited[(r, c)] = Trueif r == 0 or c == 0:pacific.add((start_r, start_c))if r == rows - 1 or c == cols - 1:atlantic.add((start_r, start_c))directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]for dr, dc in directions:nr, nc = r + dr, c + dcif 0 <= nr < rows and 0 <= nc < cols and matrix[nr][nc] <= matrix[r][c]:dfs(start_r, start_c, nr, nc, visited)visited[(nr, nc)] = False# Perform full DFS from each cell.for r in range(rows):for c in range(cols):visited = {}dfs(r, c, r, c, visited)return list(pacific & atlantic)
Approach 2: Boundary DFS
Solution
class Solution:def pacific_atlantic_flow(self, grid):if not grid or not grid[0]:return []rows, cols = len(grid), len(grid[0])# Step 1: Initialize empty setspacific_reachable = set()atlantic_reachable = set()def dfs(r, c, reachable):reachable.add((r, c))for dr, dc in [(1,0), (-1,0), (0,1), (0,-1)]:nr, nc = r + dr, c + dcif 0 <= nr < rows and 0 <= nc < cols:if (nr, nc) not in reachable and grid[nr][nc] >= grid[r][c]:dfs(nr, nc, reachable)# initializes DFS from all cells in the Atlantic and Pacific Oceans# Note how we share a single visited set# across DFS calls that originate from the same oceanfor r in range(rows):dfs(r, 0, pacific_reachable)dfs(r, cols - 1, atlantic_reachable)for c in range(cols):dfs(0, c, pacific_reachable)dfs(rows - 1, c, atlantic_reachable)# return the intersection of both sets.return list(pacific_reachable & atlantic_reachable)
Complexity Analysis
Login to track your progress
Your account is free and you can post anonymously if you choose.