Imagine you're trapped in a flooding valley represented by an n × n grid where each cell contains an elevation value. As time passes, water continuously rises - at time t, any cell with elevation ≤ t becomes submerged and navigable.

Your Goal: Find the minimum time needed to swim from the top-left corner (0,0) to the bottom-right corner (n-1, n-1).

Swimming Rules:

  • You can only move to 4-directionally adjacent cells (up, down, left, right)
  • Both your current cell and destination cell must have elevation ≤ current water level
  • You can swim infinitely fast once a path is available
  • You must stay within grid boundaries

Think of it as finding the lowest "bottleneck" elevation that blocks your escape route!

Input & Output

example_1.py — Basic 2×2 Grid
$ Input: grid = [[0,2],[1,3]]
Output: 3
💡 Note: At time 3, water level is 3. All cells are now accessible (0≤3, 2≤3, 1≤3, 3≤3). We can swim from (0,0) to (1,1) via path: (0,0) → (0,1) → (1,1) or (0,0) → (1,0) → (1,1).
example_2.py — Larger Grid with Bottleneck
$ Input: 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]]
Output: 16
💡 Note: The optimal path requires going through a cell with elevation 16, which becomes the bottleneck. Even though there are cells with higher elevations, the minimum possible maximum elevation on any path is 16.
example_3.py — Single Cell
$ Input: grid = [[5]]
Output: 5
💡 Note: Edge case: already at destination. The water level must be at least 5 to make the starting cell accessible.

Constraints

  • n == grid.length
  • n == grid[i].length
  • 1 ≤ n ≤ 50
  • 0 ≤ grid[i][j] ≤ n2 - 1
  • All values in grid are unique

Visualization

Tap to expand
Swim in Rising Water - Visual ExplanationGrid Elevations024681031591113712141516ENDSTARTGreen = Lower elevation, Red = Higher elevationWater Level ProgressLevel 5: Partial PathLevel 9: Almost ThereLevel 16: Success!Binary search finds thisefficiently in log(n) stepsBottleneck: Cell withelevation 16🌊 The key insight: Find the minimum "bottleneck" elevation that allows a complete path!Time Complexity: O(n² × log(max_elevation)) using Binary Search + DFS
Understanding the Visualization
1
Water Rises Over Time
At time t, any elevation ≤ t becomes navigable water
2
Find Minimum Bottleneck
We need the lowest water level that creates a complete path
3
Binary Search Optimization
Instead of testing every level, binary search on the answer
Key Takeaway
🎯 Key Insight: This problem is about finding the minimum bottleneck elevation on any path from start to end. Binary search on the water level combined with DFS/BFS provides the optimal O(n² × log(max_val)) solution.
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 25
67.3K Views
Medium-High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen