Problem 522333 · medium · Phase 05 Advanced Algorithms & Graphs

Wading Through the Rising Tide

graphs · binary search · BFS · grid

A tidal flat is a grid of integer heights flat (a list of equal-length lists). The water level starts at 0 and rises by one every hour. At level L you may stand on any cell whose height is at most L, and you can wade any distance instantly between up/down/left/right neighbours as long as both cells have height <= L.

Return the smallest level L at which you can get from the top-left cell to the bottom-right cell.

Examples

Input:  flat = [[0, 3, 1],
                [5, 4, 2],
                [6, 7, 1]]
Output: 3
Explanation: at level 3 the route 0 -> 3 -> 1 -> 2 -> 1 is open; at level 2 the start is cut off.

Input:  flat = [[1, 9],
                [9, 2]]
Output: 9

Constraints

  • 1 <= rows, cols and rows * cols <= 4 * 10**4, 0 <= flat[r][c] <= 10**6
  • Target O(R * C * log(maxHeight)) time.

Goals

  • Binary-search on the answer instead of searching for a path directly
  • Check a candidate level with a flood-fill BFS
  • Bound the search range by the start and end heights
Starting Python…