Best Meeting Point
Real-world version: Where to Set the Muster PointThe statement here is our own: the same inputs, outputs and technique.
A yard is given as the grid grid, where 1 marks a cell holding a worker and 0 marks an empty cell.
A worker walks one cell at a time to a cell sharing an edge with the current one, so walking between two cells costs the rows between them plus the columns between them.
Choose one cell as the muster point and add up how far every worker walks to reach it. Return the smallest total any choice of cell gives. The muster point may be any cell of the yard, whether a worker stands on it or not.
Examples
Example 1
- Input
- grid = [[1, 0, 0], [0, 0, 0], [0, 0, 1]]
- Output
- 4
The two workers stand in opposite corners. Every cell lying on a shortest walk between them costs the same, so the centre serves as well as either corner, and the total is the four steps that separate the two workers.
Example 2
- Input
- grid = [[1, 0, 1], [0, 0, 0], [1, 0, 1]]
- Output
- 8
Four workers at the corners of the yard. The two rows apart pair up for two steps, and so do the two columns, twice over, so any cell inside the square they mark costs eight steps altogether.
Example 3
- Input
- grid = [[1, 1, 1]]
- Output
- 2
All three workers share a row, so only columns matter. Mustering on the middle worker's cell costs one step from each side and nothing from the middle.
Constraints
- 1 <= grid.length <= 200
- 1 <= grid[i].length <= 200
- 0 <= grid[i][j] <= 1
- At least two cells hold a worker.
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def min_total_distance(grid: list[list[int]]) -> int:public int minTotalDistance(int[][] grid)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Minimum Operations to Make a Uni-Value GridReal-world version: Levelling A Bench Of Stepped DialsMedium
- Get Biggest Three Rhombus Sums in a GridReal-world version: Three Best Diamond Outlines on a BoardMedium
- Maximum Product of Three NumbersReal-world version: Largest Triple DriftEasy
- Missing NumberReal-world version: Unclaimed Badge NumberEasy