Swim in Rising Water

You are given an n × n grid where grid[r][c] is the elevation of cell (r, c). All elevations are distinct, and together they are exactly the numbers 0 to n² - 1.

Rain starts falling, and at time t the water everywhere is at depth t. At time t you may swim from a cell to a cell directly above, below, left or right of it if both cells have elevation at most t. Swimming takes no time: at a given moment you can cross any number of covered cells.

You start on the top-left cell (0, 0). Return the earliest time t at which you can reach the bottom-right cell (n - 1, n - 1).

Constraints

  • 1 <= n <= 50
  • grid contains every number from 0 to n² - 1 exactly once.

Examples

Example 1

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

Going down then right visits heights 0, 2 and 1, so it is usable once the water reaches 2. Going right first needs the 3 to be covered. The answer is 2.

Example 2

Input: grid = [[0,8,7],[1,6,5],[2,3,4]]
Output: 4

Down the left column and along the bottom row visits 0, 1, 2, 3, 4: at time 4 the whole route is under water.

Example 3

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

The start cell has height 3, so you can't leave it before time 3. By then the route 3 → 1 → 2 is covered.

JavaScript you'll use: Heaps and priority queues Graphs and grids in JavaScript

/**
 * @param {number[][]} grid
 * @return {number}
 */
function swimInWater(grid) {
  
}

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.