Ride-hailing app~25 min2s · 256 MBtarget O(R × C) time, O(R × C) spaceclassic twin: lc-542, lc-286grid-bfs
A scooter-share app draws a city as a grid of blocks. A block is a charging depot (D), an open street (.) or closed for road works (#).
Riders walk to the nearest depot, one block at a time to a side neighbour, and never through a closed block. The planners want the total walk of every open street, so that they can compare two depot layouts. If any open street has no way to reach a depot, the layout is invalid.
Write total_walk(city).
city is a list of equal-length rows. Each character is D, . or #.#. A depot is a walk of 0 for itself.., of the fewest blocks from it to any depot.-1 when some open street cannot reach any depot. A city with no open street has a total of 0.Input: city = ["D..#", ".#..", "...D"]
Output: 12The solution starts from both depots at once and spreads in rings. A street first reached in ring k is k blocks from its nearest depot.
| Row | Street | Walk to the nearest depot |
|---|---|---|
| 0 | D..# |
0, 1, 2, wall |
| 1 | .#.. |
1, wall, 2, 1 |
| 2 | ...D |
2, 2, 1, 0 |
The walks add up to 12.
Input: city = ["D#.", "###"]
Output: -1The open street at the end of the first row is cut off from the depot by a closed block, so the layout is invalid.
Input: city = ["..D.."]
Output: 6The walks are 2, 1, 1 and 2 on either side of the depot, which add up to 6.
1 ≤ rows ≤ 300 and 1 ≤ columns ≤ 300D, . or #There are 90,000 blocks. A search from every street would repeat about the same work 90,000 times, which is far too slow. A single search that starts from all depots at once visits each block once, so it takes about 90,000 steps.