← Google bank

Google · Question 67 · Graphs

Pacific Atlantic Water Flow

GraphsPythoncode⏱ O(rows*cols)💾 O(rows*cols)
Product-based

Problem

Find cells where water can flow to both the Pacific and Atlantic oceans in a height matrix.

Approach

Use DFS/BFS from the oceans inward and find the intersecting cells.

Time O(rows*cols)Space O(rows*cols)

How it works

  1. 1DFS from ocean borders inward where next height is not lower.
  2. 2Track reachable cells from both oceans.
  3. 3The intersection gives cells flowing to both oceans.

Sample input / output

Input:
5 5
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)]

Constraints

m == heights.length; n == heights[i].length; 1 <= m, n <= 200; 0 <= heights[r][c] <= 10^5.

Solution — read it, then walk it

Time O(rows*cols)Space O(rows*cols)Loops 3Branches 3Returns 3source · Python
Scroll sideways for wide charts — the view follows the active step.
yesnoyesno↻ repeat↻ repeat↻ repeatyesnoSTARTheightsif not heightsRETURN []rows, cols = len(heights),len(heights[0])DEFINE dfs(r, c, visited,prev_height)if (r < 0 or r >= rowsor c < 0 or c >= colsor(r, c) in visited orheights[r][c] <prev_height)RETURNvisited.add((r, c))for dr, dc in [(1, 0),(-1, 0), (0, 1), (0,-1)]dfs(r + dr, c + dc,visited, heights[r][c])pacific, atlantic = set(),set()for i in range(rows)dfs(i, 0, pacific,heights[i][0])dfs(i, cols - 1, atlantic,heights[i][cols - 1])for j in range(cols)dfs(0, j, pacific,heights[0][j])dfs(rows - 1, j, atlantic,heights[rows - 1][j])RETURN sorted(pacific &atlantic)DEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)m = int(next(it)); n =int(next(it))heights = [[int(next(it))for _ in range(n)] for _ inrange(m)]print(pacificAtlantic(heights))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/29

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits