/296. Best Meeting Point

296. Best Meeting Point

Hard
Arrays61.4% acceptance

Given a 2D binary matrix grid, where grid[i][j] = 1 represents a location of a person, find a point (row, col) such that the sum of Manhattan distances from this point to all persons is minimized. Return the minimum total distance.

Example 1

Input: [[0,0,1],[1,0,0],[0,1,0]]

Output: 4

Explanation: Optimal meeting point is at (1,1). Distances: |1-0|+|1-2|=2, |1-1|+|1-0|=1, |1-2|+|1-1|=1. Total=4.

Example 2

Input: [[1,0,0],[0,0,1],[0,1,0]]

Output: 5

Explanation: Optimal meeting point is at (1,1).

Constraints

  • 1 <= len(grid) <= 100
  • 1 <= len(grid[0]) <= 100
  • grid[i][j] is 0 or 1
  • At least one cell in grid is 1
Python (current runtime)

Case 1

Input: [[0,1,0],[0,0,1],[1,0,0]]

Expected: 4

Case 2

Input: [[1,0],[0,1]]

Expected: 2

Case 3

Input: [[1,0,0,1],[0,0,0,0],[0,1,0,0],[0,0,0,1]]

Expected: 8