You get a square grid of numbers, grid, with n rows and n columns. Each number is the height of one cell.
Return the earliest time at which you can swim from the top-left cell to the bottom-right cell.
Rain starts at time 0. At time t, the water is t deep everywhere. You can swim from a cell to a neighbour when both cells are at most t high. A neighbour is the next cell up, down, left or right.
Swimming takes no time, however far you go. You start in the top-left cell.
The grid is a vector of rows. Each row is a vector of numbers.
Example 1:
Input: grid = [ [0, 5, 2], [6, 8, 3], [7, 4, 1] ] Output: 5 Explanation: The neighbours of the top-left 0 are 5 and 6. So you can't leave it before time 5. At time 5, you can swim 0 → 5 → 2 → 3 → 1.
Example 2:
Input: grid = [ [ 0, 20, 14, 8, 9], [ 1, 17, 7, 16, 10], [ 2, 23, 6, 22, 11], [ 3, 4, 5, 19, 12], [24, 15, 21, 18, 13] ] Output: 14 Explanation: The best route goes down, then up, then down again: 0 → 1 → 2 → 3 → 4 → 5 → 6 → 7 → 14 → 8 → 9 → 10 → 11 → 12 → 13. Its highest cell is 14, so you can swim it at time 14. Every other route passes a cell that is 15 or higher.
Example 3:
Input: grid = [ [3, 0], [1, 2] ] Output: 3 Explanation: You start on a cell that is 3 high. You can't swim away from it before time 3.
Constraints:
nis from 1 to 50.- The heights are the numbers from 0 to n² - 1.
- Each height appears exactly once.
Note:
Your solution should run in O(n² log n) time.
A binary search on the time, with a BFS per guess, also takes O(n² log n).
Free plan: 30 tutor messages. Premium is unlimited.
