InterviewPrepKit

Home / Coding / Advanced Graphs

Swim in Rising Water

hard Original ↗
Solving tips
  • This is a minimax-path problem: minimize the MAXIMUM elevation along a path, not the sum, and the start cell's elevation counts too.
  • Run Dijkstra with max replacing +: a cell's priority is the water level needed to reach it, relax neighbors with max(level_so_far, neighbor_elevation), and return on first pop of the goal.
  • Alternatives: binary-search the threshold t with a BFS restricted to cells <= t, or union-find cells in ascending elevation until the corners connect.
  • Movement is 4-directional; target O(n^2 log n) time and O(n^2) space.

Problem

You’re given an n x n grid where grid[r][c] is the elevation of cell (r, c); the elevations are a permutation of 0 .. n² - 1. Rain fills the map so that at time t the water level is t: you can stand on any cell with elevation ≤ t, and you can swim between two 4-adjacent cells only if both elevations are ≤ t. Swimming takes no time.

Starting at the top-left cell (0, 0), return the earliest time t at which you can reach the bottom-right cell (n-1, n-1).

Equivalently: over all paths from top-left to bottom-right, minimize the maximum elevation along the path — a minimax path problem, not a sum-of-weights one.

Examples

  • grid = [[0,2],[1,3]]3 — every route must end on the 3, so you wait until t = 3.
  • grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]16 — snake along the rim: the path 0,1,2,3,4,5,16,15,14,13,12,11,10,9,8,7,6 never exceeds 16.
  • grid = [[3,2],[0,1]]3 — the start cell itself has elevation 3, so no matter the route you wait until t = 3.

Constraints

  • 1 <= n <= 50
  • grid contains each value 0 .. n² - 1 exactly once (all elevations distinct).

Think about it first

Hint 1 The answer to "can I cross at time t?" is monotone: if you can cross at t, you can cross at every later time. Monotone yes/no questions invite binary search.
Hint 2 Binary-search t over 0 .. n²-1; for each candidate, BFS/DFS using only cells with elevation ≤ t. That's O(n² log n). Can you skip the search and compute the threshold directly?
Hint 3 Run Dijkstra but change the path cost from sum of weights to max of elevations: the priority of a cell is the smallest water level needed to reach it, and expanding a cell relaxes neighbors with max(level_so_far, neighbor_elevation). The first time you pop the bottom-right cell, its priority is the answer.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.