---
# System prepended metadata

title: 0296. Best Meeting Point
tags: [Leetcode, Hard, Math]

---

# 0296. Best Meeting Point
###### tags: `Leetcode` `Hard` `Math`
Link: https://leetcode.com/problems/best-meeting-point/description/
## 思路
距离所有点直线距离最近的点其实就是所有点的横纵坐标取中位数
## Code
```java=
class Solution {
    public int minTotalDistance(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        List<Integer> rows = new ArrayList<>();
        List<Integer> cols = new ArrayList<>();
        for(int i=0; i<m; i++){
            for(int j=0; j<n; j++){
                if(grid[i][j]==0) continue;
                rows.add(i);
                cols.add(j);
            }
        }
        Collections.sort(rows);
        Collections.sort(cols);
        int X = rows.get(rows.size()/2), Y = cols.get(cols.size()/2);
        int ans = 0;
        for(int i=0; i<m; i++){
            for(int j=0; j<n; j++){
                if(grid[i][j]==0) continue;
                ans += Math.abs(X-i)+Math.abs(Y-j);
            }
        }
        return ans;
    }
}
```