Start learning free

LESSON 541 OF 635 · GRAPHS

Swim in Rising Water in JavaScript

Practice O(n² log n)

You get a square grid of numbers, grid, with n rows and n columns. Each number is the height of one cell.

Return the earliest time at which you can swim from the top-left cell to the bottom-right cell.

Rain starts at time 0. At time t, the water is t deep everywhere. You can swim from a cell to a neighbour when both cells are at most t high. A neighbour is the next cell up, down, left or right.

Swimming takes no time, however far you go. You start in the top-left cell.

The grid is an array of rows. Each row is an array of numbers.

 

Example 1:

Input: grid = [
  [0, 5, 2],
  [6, 8, 3],
  [7, 4, 1]
]
Output: 5
Explanation: The neighbours of the top-left 0 are 5 and 6.
So you can't leave it before time 5.
At time 5, you can swim 0 → 5 → 2 → 3 → 1.

Example 2:

Input: grid = [
  [ 0, 20, 14,  8,  9],
  [ 1, 17,  7, 16, 10],
  [ 2, 23,  6, 22, 11],
  [ 3,  4,  5, 19, 12],
  [24, 15, 21, 18, 13]
]
Output: 14
Explanation: The best route goes down, then up, then down again:
0 → 1 → 2 → 3 → 4 → 5 → 6 → 7 → 14 → 8 → 9 → 10 → 11 → 12 → 13.
Its highest cell is 14, so you can swim it at time 14.
Every other route passes a cell that is 15 or higher.

Example 3:

Input: grid = [
  [3, 0],
  [1, 2]
]
Output: 3
Explanation: You start on a cell that is 3 high.
You can't swim away from it before time 3.

 

Constraints:

  • n is from 1 to 50.
  • The heights are the numbers from 0 to n² - 1.
  • Each height appears exactly once.

Note:

Your solution should run in O(n² log n) time.

A binary search on the time, with a BFS per guess, also takes O(n² log n).

STEP 1 OF 14
    Ctrl + Enter to check

    Swim In Rising Water in JavaScript

    Keep going with JavaScript500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free