Parcel-delivery app~25 min2s · 256 MBtarget O(r c) time, O(r c) spaceclassic twin: lc-542grid-bfs
A warehouse floor is a grid of square cells. A cell holds 0 when a charging station stands on it and 1 when it is an ordinary cell. The floor always has at least one charging station.
Robots move one cell at a time to a side neighbour. Nothing blocks a move. For every cell, the fleet planner wants to know the fewest moves a robot needs to reach a charging station from there.
Write moves_to_station(floor).
floor[r][c] is 0 for a charging station and 1 for an ordinary cell. There is at least one 0.[r][c] is the fewest moves from (r, c) to any charging station, and 0 for a station itself.Input: floor = [[0, 1, 1], [1, 1, 1], [1, 1, 0]]
Output: [[0, 1, 2], [1, 2, 1], [2, 1, 0]]The solution starts one search from all stations together. The first ring of cells next to a station gets 1, the next ring gets 2, and so on. The queue holds the cells whose neighbours are still to be visited. Each cell looks at its neighbours in the order down, up, right, left.
| Step | Cell taken from the queue | New cells and their distance | Queue after |
|---|---|---|---|
| 1 | (0,0) | (1,0) = 1, (0,1) = 1 | (2,2), (1,0), (0,1) |
| 2 | (2,2) | (1,2) = 1, (2,1) = 1 | (1,0), (0,1), (1,2), (2,1) |
| 3 | (1,0) | (2,0) = 2, (1,1) = 2 | (0,1), (1,2), (2,1), (2,0), (1,1) |
| 4 | (0,1) | (0,2) = 2 | (1,2), (2,1), (2,0), (1,1), (0,2) |
| 5 to 9 | (1,2), (2,1), (2,0), (1,1), (0,2) | none: every cell has a distance | empty |
Input: floor = [[0]]
Output: [[0]]The only cell is a station.
Input: floor = [[0, 1, 1, 0]]
Output: [[0, 1, 1, 0]]Each ordinary cell is one move from a station.
1 ≤ floor.length ≤ 100 and 1 ≤ floor[r].length ≤ 100 (a rectangle)A grid has up to 10,000 cells. Comparing every cell with every station costs up to 10,000 × 10,000 = 10^8 steps in the worst case, and a search from every cell is slower still. One search that starts from all stations visits each cell once, about 10,000 visits.