Menu
CoddyTech

Swim in Rising Water

You get an n × n grid of heights that holds every number from 0 to n²-1 exactly once, as a list of rows. Rain starts at time 0, and at time t the water stands at height t everywhere, so every cell of height t or less is under water. You start in the top left cell. You can swim from a cell to a cell that shares a side with it when both are under water, and swimming takes no time. Return the earliest time at which you can be in the bottom right cell.

Function

swimInWater(grid: integer-2d-array) → integer
gridinteger-2d-array
the heights, as a list of n rows of n numbers
Returnsinteger
the earliest time you can reach the bottom right cell

Constraints

  • n == grid.length == grid[i].length
  • 1 ≤ n ≤ 100
  • 0 ≤ grid[i][j] ≤ n²-1
  • Every value from 0 to n²-1 appears exactly once.

Examples

Input
grid = [[0, 2], [3, 1]]
Output
2
Explanation
Through the top right cell the route is 0, 2, 1, and its highest cell is 2. Through the bottom left cell it is 0, 3, 1, with highest cell 3. At time 2 the first route is under water, so the answer is 2.

lock icon+13 hidden tests on Submit

challenge icon

Follow-up

If heights could repeat and reach 10^9, which of your approaches still works unchanged, and what would you binary search over?

Reset code
def swimInWater(grid):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

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

Expected

2