Ride-hailing app~25 min2s · 256 MBtarget O(rows x cols) time, O(rows x cols) spaceclassic twin: lc-934grid-bfs · shortest-paths
A ride-hailing app divides a city into square blocks on a grid. A block marked 1 is inside a service zone, and a block marked 0 is not. Zones connect through shared sides, not corners.
The grid holds exactly two zones. The app can extend service to uncovered blocks, one block at a time. You want the fewest blocks to add so that the two zones become one zone.
Write fewest_connectors(city).
city is a rectangle of rows, each a list of 0 and 1. A 1 is a covered block.Input: city = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]
Output: 1The outer frame is one zone, and the single block in the centre is the other. Covering the block above the centre joins them, so one block is enough.
The solution marks the first zone and then grows a ring outwards, one step at a time, over uncovered blocks. It stops when the ring is next to a covered block that is not in the first zone.
| Ring | Uncovered blocks reached | Next to the second zone? |
|---|---|---|
| 0 | none yet, the ring is the frame | no |
| 1 | the 8 uncovered blocks inside the frame | yes, the centre |
The ring stops after 1 round of growth with the centre next to it, so the answer is 1.
Input: city = [[1,0,1]]
Output: 1One uncovered block separates the zones.
Input: city = [[1,1,0,0,1]]
Output: 2Two uncovered blocks separate the zones.
1 ≤ city.length ≤ 300 and 1 ≤ city[i].length ≤ 300, and every row has the same lengthA grid of 300 × 300 has 90,000 blocks, and a zone may hold 45,000 of them. Comparing every block of one zone with every block of the other costs up to 45,000 × 45,000 = 2 × 10^9 steps. Growing a ring touches each block once, about 90,000 × 4 steps.