Online store~25 min2s · 256 MBtarget O(r c) time, O(r c) spaceclassic twin: lc-994grid-bfs
The stock room of a shop is a grid of bays. A bay is open floor (0), fixed shelving (1), a dock of the morning team (2) or a dock of the evening team (3).
Each team sends robots out from all its docks at once. Every minute a robot moves one bay up, down, left or right, onto any bay that is not shelving. A bay belongs to the team whose robot reaches it first. When both teams arrive in the same minute, the bay is contested.
Write dock_service(floor).
floor[r][c] is 0, 1, 2 or 3, as described above. There may be no dock of a team.[a, b, contested, minutes]: the bays served by the morning team, by the evening team and contested, and the minute when the last served bay is first reached.Input: floor = [[2,0,0,0,3],[0,1,1,0,0],[0,0,0,0,0]]
Output: [5, 6, 2, 4]Two searches run from the docks, one for each team. A bay's first arrival is the smaller of its two distances. The table groups the bays by that minute, as (row, column).
| Minute | Morning team | Evening team | Contested |
|---|---|---|---|
| 0 | (0,0) | (0,4) | |
| 1 | (0,1), (1,0) | (0,3), (1,4) | |
| 2 | (2,0) | (1,3), (2,4) | (0,2) |
| 3 | (2,1) | (2,3) | |
| 4 | (2,2) |
That is 5 bays, 6 bays and 2 contested bays. The last bay, (2, 2), is first reached in minute 4.
Input: floor = [[2,1,0]]
Output: [1, 0, 0, 0]The shelving cuts off the right bay, so no team reaches it. Only the dock itself is counted.
Input: floor = [[2,0,3]]
Output: [1, 1, 1, 1]Both robots reach the middle bay in minute 1, so it is contested.
1 ≤ rows, columns ≤ 300floor is 0, 1, 2 or 3A floor has up to 300 × 300 = 90,000 bays. Searching outwards from every bay to find its nearest docks can cost 90,000 steps per bay, so about 8.1 × 10^9 steps in total. One search per team, started from all its docks together, visits each bay once and costs O(r c).