ntree.ai
ntree.aiSwim in Rising Water

Swim in Rising Water

hardsolvedattempted

You are given an n x n grid where grid[r][c] is the height of the ground at that cell. Every value from 0 to n² - 1 appears exactly once.

Rain starts at time 0, and at time t the water everywhere is t deep. You can swim from a cell to a neighbour horizontally or vertically whenever both cells have a height of at most t. Swimming itself takes no time.

Starting at the top-left cell, return the earliest time at which you can reach the bottom-right cell.

Example 1:

Input:  grid = [[0, 2],
                [1, 3]]
Output: 3
Explanation: you can only enter the bottom-right cell, of height 3, once the water is 3 deep.

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
Explanation: the path follows the spiral; the highest cell it must cross has height 16.

Constraints:

  • 1 <= n <= 50
  • 0 <= grid[r][c] < n²
  • every value in grid is distinct
def swimInWater(grid: list[list[int]]) -> int:
pass
 
0
2
1
3

Press Visualise to step through your code.