Parcel-delivery app~25 min2s · 256 MBtarget O(r c) time, O(r c) spaceclassic twin: lc-1091grid-bfs
A warehouse uses a drone to carry small parcels between bays. The floor plan is a rectangle of bays, and each bay is clear (0) or holds a rack (1).
The drone flies from the top-left bay to the bottom-right bay. One move takes it to any of the eight bays around it. A diagonal move passes between two bays, the ones beside the move. The drone cannot squeeze through when both of those bays hold racks.
Write fewest_flight_moves(grid).
grid[r][c] is 0 for a clear bay and 1 for a rack.(r, c) to (r + dr, c + dc) is blocked when both (r + dr, c) and (r, c + dc) hold racks.-1 when no route exists. A start or goal bay with a rack has no route.Input: grid = [[0,0,1,0],[0,0,1,1],[0,1,0,0],[0,0,0,0]]
Output: 5A drone that could cut corners would fly straight down the diagonal in 3 moves. The move from (1, 1) to (2, 2) is blocked, because (2, 1) and (1, 2) are both racks.
A queue visits the bays in rings of equal distance. The table lists the bays of each ring, as (row, column).
| Moves | Bays reached at this distance |
|---|---|
| 0 | (0,0) |
| 1 | (0,1), (1,0), (1,1) |
| 2 | (2,0) |
| 3 | (3,0), (3,1) |
| 4 | (2,2), (3,2) |
| 5 | (2,3), (3,3) |
The goal (3, 3) first appears at 5 moves.
Input: grid = [[0,1],[1,0]]
Output: -1The only way out of the start is the diagonal move, and both bays beside it hold racks.
Input: grid = [[0]]
Output: 0The start is also the goal, so no move is needed.
1 ≤ rows, columns ≤ 300grid is 0 or 1A grid has up to 300 × 300 = 90,000 bays and eight moves from each, so about 720,000 moves are tried once. Repeating a full pass over the grid until no distance improves can need a pass for every turn of a winding route. A queue that visits each bay once costs O(r c).