You are given an n x n integer matrix grid where grid[i][j] is the elevation of the square at (i, j).
Rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from a square to a 4-directionally adjacent square if and only if the elevations of both squares are at most t. Swimming takes no time, so you can cover any distance instantly, but you must stay inside the grid.
Return the least time at which you can reach the bottom-right square (n - 1, n - 1) starting from the top-left square (0, 0).
Function Signature
def swim_in_water(grid: List[List[int]]) -> int:
Rules
-
grid
is a list of
n
rows, each a list of
n
integers.
-
Time takes integer values, and the answer is the smallest integer
t
at which a path from
(0, 0)
to
(n - 1, n - 1)
exists.
Constraints
-
n == len(grid) == len(grid[i])
-
1 <= n <= 50
-
0 <= grid[i][j] < n^2
-
Every value in
grid
is unique.
Examples
Input: grid = [[0,2],[1,3]]
Output: 3
The target square itself has elevation 3, so no earlier time can work. At time 3 every square is open and the route (0,0) -> (1,0) -> (1,1) has highest elevation max(0, 1, 3) = 3.
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
Row 1 is 24, 23, 22, 21, 5, so below time 21 the only way out of the top row is (1,4) at elevation 5, and from there the next squares are (2,4) at 16 and (1,3) at 21. At time 16 the route runs along the top row, down to (2,4), west along row 2 to (2,0), down to (4,0) and east along the bottom row to (4,4). Its highest square is 16.
Input: grid = [[0,3,8],[1,7,2],[6,5,4]]
Output: 6
From the squares with elevations 0, 1 and 3, every route to the bottom-right corner has to enter a square of elevation 6, 7 or 8. The cheapest goes down the left column and along the bottom row through 0, 1, 6, 5, 4, so its highest square is 6.