Buildings Meeting Distance Problem

Buildings Meeting Distance Problem — ExecCode Hard DSA Practice

Solve the Buildings Meeting Distance problem on ExecCode. Free online hard DSA practice in Graph. Write and run code in Java, C++, Python — no signup required to run.

Problem description

Grid: 0 empty, 1 building, 2 obstacle. You must pick an empty cell that can reach every building, minimizing the sum of Manhattan walking distances to all buildings (4-dir, obstacles blocked). If none exists, -1. Return the minimum distance sum, or -1. You are given: grid — matrix of 0/1/2 Return integer or -1. If there are no empty cells, return -1.

Examples

Input {'grid': [[1, 0, 2, 0, 1], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0]]}; Output 7. Input {'grid': [[1, 2, 0]]}; Output -1. Input {'grid': [[1]]}; Output -1

Constraints

You cannot land on a building or obstacle Distance is number of steps

Practice Buildings Meeting Distance free on ExecCode. Browse DSA problems, topic map, and placement guides.