Ctrl K

A House Close to Every Building

Hard
A block plan is an m × n table plan, where every cell holds one of these values: - 0: open land you can walk on; - 1: a building you cannot walk through; - 2: an obstacle you cannot walk through either. A house is to be built on one of the open cells. You may only move up, down, left and right across open cells; the distance from the house to a building is the fewest steps from the house cell to the building cell (the last step lands on the building itself). Pick an open cell from which every building can be reached and the total distance to all buildings is as small as possible, and return that total. If there is no such cell, return -1.
Example 1
plan=[[1, 0, 0, 1], [0, 2, 0, 0], [0, 0, 0, 1]] → 6

The best spot is (0, 2): the buildings are 2, 1 and 3 steps away, 6 in total. Cell (0, 1), for instance, gives 1 + 2 + 4 = 7, which is worse.

Example 2
plan=[[1, 2, 0], [2, 0, 0], [0, 0, 1]] → -1

The building in the top-left corner is walled in, so no empty cell can reach it.

Example 3
plan=[[0, 1, 0]] → 1

Both empty cells are right next to the building.

Constraints
  • 1 ≤ m, n ≤ 50
  • plan[i][j] is 0, 1 or 2
  • There is at least one building
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFrame Around an Ink Blot HardLongest Uphill Walk HardRain Pools on a Relief Map HardBall Into the Hole HardTrim the Bushes, Shortest First Hard
loading Python…
Input
plan=[[1, 0, 0, 1], [0, 2, 0, 0], [0, 0, 0, 1]]
Expected
6

Run checks the first 3 tests in your browser. Submit checks all 89 tests on the server, hidden ones included.