Swim in Rising Water

You are in an n x n grid where grid[i][j] is the elevation of the cell. You can move in four directions, and you may enter a cell only when the water level is at least its elevation. Return the minimum time required to swim from the top-left cell to the bottom-right cell. Pattern focus: Prim/Dijkstra on a grid with a minimax objective.

Input Format

grid = n x n matrix of distinct elevations

Output Format

minimum time required to reach the bottom-right cell

Constraints

  • 1 <= n <= 100
  • n*n <= 10^4
  • 0 <= grid[i][j] < n*n
  • All values are distinct.

Examples

Example 1:

Input:

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

Output:

3

Explanation:

You must wait until time 3 to reach the destination.

Example 2:

Input:

grid = [[0,1,2,3,4]]

Output:

4

Explanation:

In a single row, the answer is the largest elevation on the only path.

Example 3:

Input:

grid = [[7]]

Output:

7

Explanation:

The start is the end, so the time is the starting cell's elevation.

Loading...
Swim in Rising Water - Advanced Graphs