Maps app~30 min2s · 256 MBtarget O(r c log V) time, O(r c) spacebinary-search-answer
A maps app rates the surface of every tile of a delivery area with a roughness score from 0 to 1,000,000. A small robot leaves from the top-left tile and must reach the bottom-right tile. It moves one tile at a time to a neighbour on its left, right, above or below.
The robot's suspension is tuned to the roughness of the tile it starts on. It can roll over a tile only when that tile's roughness is within a tolerance d of the starting tile's roughness, in either direction. The tuning team wants the smallest tolerance that lets the robot arrive.
Write smallest_tolerance(tiles).
tiles[r][c] is the roughness of the tile in row r and column c.|tiles[r][c] - tiles[0][0]| <= d. The start tile is always allowed.d for which a route from the top-left tile to the bottom-right tile exists.Input: tiles = [[20, 90, 35], [70, 25, 60], [40, 30, 28]]
Output: 50The start tile has roughness 20. The tolerance must be at least 8, the difference to the last tile, which has roughness 28. It never needs to be more than 70, the largest difference to the start in the grid. The trace tests a tolerance and keeps the lower half or the upper half of the range.
| lo | hi | d tested | Route exists? | Decision |
|---|---|---|---|---|
| 8 | 70 | 39 | no | lo becomes 40 |
| 40 | 70 | 55 | yes | hi becomes 55 |
| 40 | 55 | 47 | no | lo becomes 48 |
| 48 | 55 | 51 | yes | hi becomes 51 |
| 48 | 51 | 49 | no | lo becomes 50 |
| 50 | 51 | 50 | yes | hi becomes 50 |
With d = 49 both neighbours of the start have a difference of 70 - 20 = 50 or more, so the robot cannot leave. With d = 50 the tile with roughness 70 opens, and a route follows.
Input: tiles = [[7]]
Output: 0The robot is already at the goal.
Input: tiles = [[0, 9], [9, 0]]
Output: 9The robot has to cross a tile of roughness 9, because it cannot move diagonally.
1 ≤ tiles.length ≤ 100 and 1 ≤ tiles[r].length ≤ 100 (a rectangle)0 ≤ tiles[r][c] ≤ 1,000,000Trying the tolerances 0, 1, 2 and so on, with a full search of the grid each time, costs up to 10^6 × 10^4 = 10^10 steps. That is far over the budget of about 10^8 a second. A larger tolerance never closes a route, so a halving search needs only about 20 grid searches.