Problem Description
Given an m x n binary grid where each 1 marks the home of one friend, the goal is to find a meeting point (an empty cell) that minimizes the total travel distance from all the friends’ houses. The travel distance is defined by Manhattan Distance: the sum of absolute differences of the x and y coordinates.
Key Insights
- The optimal meeting point in one dimension is the median of the coordinates, which minimizes the sum of absolute deviations.
- We can handle the two dimensions (rows and columns) independently by collecting the row and column indices of each friend.
- Sorting the coordinates or traversing in a smart order (for instance, rows are naturally sorted when scanning row-wise) allows easy extraction of the median.
- The total minimum distance is the sum of the absolute differences between each friend’s row/column index and the median row/column index.
Space and Time Complexity
Time Complexity: O(m*n) to traverse the grid and O(F) to compute the distance, where F is the number of friends (1s in grid).
Space Complexity: O(F) for storing the row and column indices of the friends.
Solution
The solution first collects all the row indices and column indices of the friend locations. For the row indices, a simple row-wise traversal suffices as they will be naturally sorted. For the column indices, iterate column-by-column to get sorted order. Next, the median position is computed for both rows and columns. This median minimizes the sum of distances on that axis. Finally, compute the total Manhattan distance from each friend’s location to the median point by summing up the absolute differences between their indices and the medians. The key trick is understanding that Manhattan distance minimization can be split into two 1D problems, each solved by the median.