Shortest Distance from All Buildings

Hard · Queue & Deque · about 35 minutes

Asked at Meta, Google, DoorDash, ByteDance, Microsoft.

An m × n grid has 0 (empty land you can walk through), 1 (a building, not walkable) and 2 (an obstacle). Build a house on an empty cell that reaches every building, minimizing the total walking distance (4 directions). Return that minimum total, or -1 if no such cell exists.

Related guides