Ride-hailing app~35 min2s · 256 MBtarget O(r c log(r c)) time, O(r c) spaceclassic twin: lc-778dijkstra
After a street event, the blocks of a city grid are closed and reopen on a timetable. A scooter courier wants to reach the bottom-right block from the top-left block.
Block (r, c) reopens at minute opens[r][c], and stays open after that. A move to a neighbouring block above, below, left or right takes one minute. The courier may wait on an open block for as long as needed.
Write earliest_arrival(opens).
opens[r][c] is the minute from which the block can be entered or stood on.opens[0][0] on the top-left block. That block is not open before then.Input: opens = [[1,9,3],[4,8,2],[6,7,5]]
Output: 8A heap holds the blocks with their earliest known arrival minute. The block with the smallest minute comes out first, and each move gives max(minute + 1, opens of the new block).
| Minute | Block taken from the heap | Reason |
|---|---|---|
| 1 | (0,0) | the start, at its opening minute |
| 4 | (1,0) | one move gives minute 2, but the block opens at 4 |
| 6 | (2,0) | opens at 6 |
| 7 | (2,1) | 6 + 1 = 7, and it opens at 7 |
| 8 | (1,1) | 7 + 1 = 8, and it opens at 8 |
| 8 | (2,2) | 7 + 1 = 8, and it opens at 5, so 8 |
The courier reaches the goal at minute 8. A route through the top row would need minute 9 for block (0,1).
Input: opens = [[5]]
Output: 5The start is the goal, and the courier is there from minute 5.
Input: opens = [[0,0],[0,0]]
Output: 2Every block is open, so the courier needs the two moves of the shortest route.
1 ≤ rows, columns ≤ 3000 ≤ opens[r][c] ≤ 1,000,000The answer can be as large as 10^6, so following the minutes one by one over 90,000 blocks costs up to 9 × 10^10 steps. Dijkstra's algorithm needs to settle each block once, and costs O(r c log(r c)), about 1.5 × 10^6 steps.