Swim in Rising Water

IF
AlgoAxiomStaff Engineers
JSTS
Hard20 mins

You are given an n x n integer matrix grid where grid[i][j] represents the elevation at that position. At time t, the depth of the water everywhere is t.

You can swim from one cell to an adjacent (4-directional) cell in one step if and only if the maximum elevation along your path so far is at most t.

Return the minimum time until you can reach the bottom right cell (n-1, n-1) starting from the top left cell (0, 0).

Examples

Example 1:

Input: grid = [[0,2],[1,3]]

Output: 3

Explanation: At time 3 you can travel along path (0,0)→(1,0)→(1,1). The max elevation on this path is max(0,1,3)=3.

Example 2:

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

Explanation: The optimal path has a maximum elevation of 16.

Example 3:

Input: grid = [[0]]

Output: 0

Explanation: Already at the destination.

Constraints

  • n == grid.length == grid[i].length
  • 1 <= n <= 50
  • 0 <= grid[i][j] < n^2
  • Each value grid[i][j] is unique.
Source: K-way Merge pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle