You get an n × n grid of distinct whole numbers, where grid[r][c] is the height of that square. Rain starts, and at time t the water stands at level t.
You start in the top-left square and swim up, down, left or right. You may move between two neighbouring squares at time t only if both heights are at most t. Swimming itself takes no time, so you can cross any distance in an instant.
Return the earliest time at which you can get to the bottom-right square.
Example 1
Input: grid = [[0, 5, 4],
[2, 8, 1],
[6, 7, 3]]
Output: 5
Why: the route 0 → 5 → 4 → 1 → 3 never goes above 52 more examples and the constraints
Example 2
Input: grid = [[0, 1], [2, 3]] Output: 3 Why: the goal itself has height 3
Example 3
Input: grid = [[0]] Output: 0 Why: you start on the goal
Constraints
- 1 ≤ n ≤ 50
- The grid holds every number from 0 to n² − 1 exactly once
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Binary search on the timeO(n² log n)
- Min-heap (Dijkstra)O(n² log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 50 × 50 grid | Verdict |
|---|---|---|---|
| Binary search on the time | O(n² log n) | Passes; a dozen flood fills | |
| Min-heap (Dijkstra) | O(n² log n) | Best; one sweep, stops at the goal |
n = side of the grid, so there are n² cells.
Edge cases to test
- One cell. [[0]] is already at the goal: the answer is 0.
- High start. In [[3, 2], [0, 1]] you cannot even leave until t = 3, so the answer is 3.
- High goal. The goal’s own height is a floor on the answer, as in [[0, 1], [2, 3]].
- Long detour. The best route may wind all the way round the grid, like a spiral, rather than go straight.
Common mistakes
- Adding heights along the route, as in a shortest path, instead of taking the maximum.
- Forgetting the start’s own height: you cannot leave (0,0) before t = grid[0][0].
- Using a plain queue instead of a min-heap, so cells come out in the wrong order and the answer can be too high.
How to talk through it
- 1Clarify. Does swimming take time? (No.) Are heights distinct? Is the start’s height part of the answer?
- 2Reframe. A route costs its highest cell. We want the route with the lowest such cost: a minimax path.
- 3Give the binary search. For a fixed t, a flood fill says yes or no, and yes stays yes as t grows. Binary search on t.
- 4Code the heap. Dijkstra with max instead of plus: pop the cheapest cell, push neighbours at max(t, height), stop at the goal.
- 5Test out loud. Run one cell, a high start and a spiral that forces a long detour.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?