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. 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, in no time, to a cell that shares a side with yours when both are under water. 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, with highest cell 2. Through the bottom left it is 0, 3, 1, with highest cell 3. At time 2 the first route is under water.
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 #1

Test #2

Test #3

Argument

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

Expected Output

2