Problem Description
Given a grid where each cell represents an empty land (0), a building (1), or an obstacle (2), the goal is to find an empty land such that the sum of Manhattan distances from this land to all buildings is minimized. You can move only up, down, left, or right. Return the minimum sum of distances. If no such empty land exists that can reach all buildings, return -1.
Key Insights
- We need to compute the Manhattan distance from each building (cell value 1) to all empty lands (cell value 0) by performing a BFS.
- Maintain two matrices: one for cumulative total distances and another for the count of buildings that reached a particular empty cell.
- Ensure that only those empty cells reachable by every building are considered.
- The ideal cell will have a reach count equal to the total number of buildings.
- If multiple buildings cannot all reach any specific empty cell, then return -1.
Space and Time Complexity
Time Complexity: O(k * m * n) where k is the number of buildings and m,n are the grid dimensions. Space Complexity: O(m * n) due to the auxiliary matrices and visited state tracking used in BFS.
Solution
We first iterate through the grid to locate all buildings while counting them. For each building, we perform a BFS to compute the shortest distance to each reachable empty cell. During the BFS, we update the cumulative distance for that cell and record that it was reached by one additional building. After processing all the buildings, we scan the grid to find the empty cell that is reachable from all buildings and has the minimum cumulative distance. If no such cell exists, we return -1.