A town planner wants to put a new post office on an empty lot so that the people in every existing building walk as little as possible in total. People walk one block at a time up, down, left or right. They can walk across empty lots, but not through other buildings or through obstacles such as ponds and fenced parks.
The town is grid, an array of rows where 0 is an empty lot, 1 is a building and 2 is an obstacle. The walking distance from a building to a lot is the fewest steps from the building to that lot, stepping only onto empty lots. A lot is eligible if every building can walk to it.
Write two functions:
shortestTotalWalk(grid) returns the smallest sum, over all buildings, of the walking distance to one eligible lot, or -1 if no lot is eligible.
bestLot(grid) returns that lot as [row, col], or null if no lot is eligible. If several lots tie, return the one with the smallest row, then the smallest column.
Rules:
If grid is not a non-empty rectangular array of rows containing only 0, 1 and 2, throw a TypeError. A grid with no building throws a RangeError.
Do not change the grid.
Grids can be 150 × 150 with up to 50 buildings. A BFS from every empty lot does about 500 million steps there and is far too slow.
const town = [ [1, 0, 2, 0, 1], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0],];shortestTotalWalk(town); // 7: 3 + 3 + 1 from the lot at [1, 2]bestLot(town); // [1, 2]bestLot([[1, 1], [0, 0]]); // [1, 0]: both lots total 3, the earlier one winsshortestTotalWalk([[1, 2, 0, 0, 1]]); // -1: the pond splits the town
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
2
code listings
6
edge cases
What's inside
The full problem, with examples
Tests that check your solution
Step-by-step
Approach
Solution
Complexity
Edge cases
Follow-up questions
Card worldwide
UPI and net banking in India
One-time payment, nothing renews
Private, and saved in this browser as you type. All your notes are on My lists.