/317. Shortest Distance from All Buildings

317. Shortest Distance from All Buildings

Hard
Arrays44.9% acceptance

Given a 2D integer matrix grid, where each cell is either 0 (empty land), 1 (building), or 2 (obstacle), find the minimum sum of distances from an empty land cell to all buildings. You may move up, down, left, or right. Return the minimum sum of distances among all empty land cells that can reach all buildings. If no such cell exists, return -1.

Example 1

Input: [[0,2,1],[0,0,0],[1,2,0]]

Output: 7

Explanation: The cell at (2,2) can reach both buildings with a total distance of 7.

Example 2

Input: [[1,2,0],[0,2,1],[0,0,0]]

Output: 6

Explanation: The cell at (2,0) can reach both buildings with a total distance of 6.

Constraints

  • 1 <= len(grid) <= 50
  • 1 <= len(grid[0]) <= 50
  • Each cell in grid is 0, 1, or 2
  • There is at least one building (1) in grid
  • Movement is allowed only in four directions: up, down, left, right
Python (current runtime)

Case 1

Input: [[0,1,0],[2,0,2],[1,0,0]]

Expected: 5

Case 2

Input: [[1,0,2,0],[0,0,2,1],[2,0,0,0]]

Expected: 7

Case 3

Input: [[1,2,2],[2,0,2],[2,2,1]]

Expected: -1