CodeArchon

hardAdvanced GraphsGoogle

Rising Tide Pathfinder

A swimmer in a bowl-shaped grid can enter cell (r,c) only when the tide ≥ its elevation. Find the earliest tide reaching bottom-right.

Given an n×n elevation grid, return the minimum tide time t such that there exists a path from (0,0) to (n-1,n-1) using cells with elevation ≤ t.

Choose approach

0
cur
2
1
3
1/5
Narrationstep 1 of 5

Settle (0,0) at tide 0.

1import heapq
2def swimInWater(g):
3 n = len(g)
4 seen = [[False]*n for _ in range(n)]
5 pq = [(g[0][0], 0, 0)]
6 while pq:
7 t, r, c = heapq.heappop(pq)
8 if r == n - 1 and c == n - 1: return t
9 if seen[r][c]: continue
10 seen[r][c] = True
11 for dr, dc in [(1,0),(-1,0),(0,1),(0,-1)]:
12 nr, nc = r+dr, c+dc
13 if 0 <= nr < n and 0 <= nc < n and not seen[nr][nc]:
14 heapq.heappush(pq, (max(t, g[nr][nc]), nr, nc))
15 return -1
Variables
r=0
c=0
tide=0

How to think about it

  1. Each cell has a 'cost' = elevation; path cost = max cell along path.
  2. Classic Dijkstra generalization: relax = max.
  3. Early exit when the goal pops.

Edge cases to catch in interview

  • 1×1 grid -> grid[0][0].
  • Monotonic staircase -> last cell's value.

Examples

Example 13
{"grid":[[0,2],[1,3]]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed