 All Problems
Swim in Rising Water
hard
union-find
binary search
heap
graph
google
amazon

You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at point (i, j).

Rain falls. At time t, the depth of the water everywhere is t. You can swim from a square to an adjacent square (4-directionally) if both squares have elevations at most t.

Return the least time until you can swim from the top-left to the bottom-right corner.

Example 1:

Input: grid = [[0,2],[1,3]]
Output: 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

Constraints:

  • n == grid.length == grid[i].length
  • 1 <= n <= 50
  • 0 <= grid[i][j] < n^2
Run to check your code against the sample cases, or submit to run every case