317. Shortest Distance from All Buildings

Problem

Find the empty land cell that minimizes the total travel distance to all buildings.

You are given a 2D grid with:

  • 0 = empty land (can be built on)
  • 1 = building
  • 2 = obstacle

Find an empty cell such that the total Manhattan distance to all buildings is minimized. Return the minimum total distance, or -1 if no such cell exists.

Examples
Input: [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]]
Output: 7
Hints
Related Problems

317. Shortest Distance from All Buildings

Find the empty land cell that minimizes the total travel distance to all buildings.