Best Meeting Point

Hard · Matrix · Array · Math · Sorting · Matrix

Problem

You are given an m x n grid of 0s and 1s, where each 1 is the home of one friend. The friends want to meet at a single cell, any cell at all, including one with a home, so that the total distance they travel is as small as possible.

Distance is measured along the grid lines: from (r1, c1) to (r2, c2) is |r1 - r2| + |c1 - c2|.

Return the smallest possible total distance.

Examples

Input: grid = [[1,0,1],[0,0,0],[0,1,0]]
Output: 4

Meeting at (0, 1) costs 1 + 1 + 2 = 4, and no cell does better.

Input: grid = [[1,1]]
Output: 1

Meeting at either home costs 1.

Input: grid = [[0,1],[0,0],[1,0]]
Output: 3

Any cell on a shortest route between the two homes works, and the distance between them is 3.

Constraints

Approaches

Follow-up

If the meeting cell must be empty, or walls block some paths, the coordinates are no longer independent and the trick fails; a BFS from every home (summing the distances per cell) is then needed. If the distance is straight-line instead of along the grid, the best point is the geometric median, which has no closed form and is found by iterative methods.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…