Interesting one.. I can feel sparkle in mind in the proposed solution - just pick the mid-point! (yes some boiler-plate code below)
class Solution { // Greedy solutionpublic: int minTotalDistance(vector>& grid) { int n = grid.size(); int m = grid[0].size(); // Record - O(m*n) vector hori(m); vector vert(n); for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) { if(grid[i][j]) { hori[j]++; vert[i]++; } } // Expand records - O(k) vector horis, verts; for(int i = 0; i < hori.size(); i ++) { int v = hori[i]; if(v) { for(int j = 0; j < v; j++) horis.push_back(i); } } for(int i = 0; i < vert.size(); i ++) { int v = vert[i]; if(v) { for(int j = 0; j < v; j++) verts.push_back(i); } } // Get point coords size_t hcnt = horis.size(), vcnt = verts.size(); int mid_h = (hcnt % 2) ? horis[hcnt/2] : ((horis[hcnt/2] + horis[hcnt/2 - 1]) / 2); int mid_v = (vcnt % 2) ? verts[vcnt/2] : ((verts[vcnt/2] + verts[vcnt/2 - 1]) / 2); int ret = 0; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) { if(grid[i][j]) { ret += abs(i - mid_v) + abs(j - mid_h); } } return ret; }};