Skip to problem
←

Swim in Rising Water

Hard 0 attempts

Each cell in an n × n grid has an elevation. At time t, the water level is t, and you may occupy only cells whose elevation is at most t.

Find the earliest time when you can travel from the top-left cell [0,0] to the bottom-right cell [n-1,n-1].

Move only up, down, left, or right; diagonal moves are not allowed. Both endpoints must also be submerged. Movement itself takes no additional time: at a fixed water level, you may traverse any connected group of eligible cells.

Equivalently, minimize the highest elevation encountered along a path. Return that elevation, not the number of moves or the sum of elevations.

Function contract

Implement swimInWater(grid).

Output: Return the earliest water level t at which a four-direction path connects the top-left and bottom-right cells.

Example 1

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

Example 2

Input
grid = [[0]]
Output
0
Constraints
  • grid is an n × n square matrix
  • 1 <= n <= 50
  • 0 <= grid[i][j] < n^2
  • Each value in grid is unique

Binary Search with BFS Reachability

A water level is feasible if BFS can reach the destination using only cells no higher than that level. Once a level is feasible, every higher level is feasible too, so binary search finds the first feasible level.

The lower bound is the larger endpoint elevation. The upper bound n² - 1 makes every cell available under the unique-elevation constraints.

javascript
function swimInWater(grid) {
  const n = grid.length,
    dirs = [
      [0, 1],
      [0, -1],
      [1, 0],
      [-1, 0],
    ];
  let lo = Math.max(grid[0][0], grid[n - 1][n - 1]),
    hi = n * n - 1;
  while (lo < hi) {
    const mid = (lo + hi) >> 1;
    const visited = Array.from({ length: n }, () => Array(n).fill(false));
    const q = [[0, 0]];
    visited[0][0] = true;
    let head = 0;
    while (head < q.length) {
      const [r, c] = q[head++];
      for (const [dr, dc] of dirs) {
        const nr = r + dr,
          nc = c + dc;
        if (
          nr >= 0 &&
          nr < n &&
          nc >= 0 &&
          nc < n &&
          !visited[nr][nc] &&
          grid[nr][nc] <= mid
        ) {
          visited[nr][nc] = true;
          q.push([nr, nc]);
        }
      }
    }
    if (visited[n - 1][n - 1]) hi = mid;
    else lo = mid + 1;
  }
  return lo;
}

Time: O(n² log n) | Space: O(n²)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript