Ctrl K

Where the Friends Should Meet

Hard
The city is an m × n grid city: city[i][j] = 1 if one of the friends lives in cell (i, j), and 0 otherwise. The friends want to pick a meeting cell (any cell, including someone's home) so that the total distance everyone walks to it is as small as possible. They can only walk horizontally and vertically, so getting from (r₁, c₁) to (r₂, c₂) takes |r₁ - r₂| + |c₁ - c₂|. Return the smallest possible total walk.
Example 1
city=[[0, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0]] → 5

The friends live at (0, 1), (1, 3) and (2, 0). Meeting at (1, 1) costs 1 + 2 + 2 = 5, and nothing is cheaper.

Example 2
city=[[1], [0], [0], [1]] → 3

Any cell between the two homes gives a total walk of 3.

Example 3
city=[[1, 0, 1], [0, 0, 0], [1, 0, 1]] → 8
Constraints
  • 1 ≤ m, n ≤ 200
  • All rows of city have the same length n
  • city[i][j] is 0 or 1
  • At least two friends live in the city
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsHow a Rumor Spreads EasyThree Heaviest Diamonds MediumLevel the Grid in Steps MediumCheckerboard by Swapping Lines HardSpread Over All Selections Hard
loading Python…
Input
city=[[0, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0]]
Expected
5

Run checks the first 3 tests in your browser. Submit checks all 71 tests on the server, hidden ones included.