def minTotalDistance(self, grid):
x = sorted([i for i, row in enumerate(grid) for v in row if v == 1])
y = sorted([j for row in grid for j, v in enumerate(row) if v == 1])
return sum([abs(x[len(x)/2]i)+abs(y[len(y)/2]j) for i, row in enumerate(grid) for j, v in enumerate(row) if v == 1])
3Line Python Solution


Very good solution! Thanks for your sharing :)
BTW, translating it to C++ makes it so ugly...
class Solution { public: int minTotalDistance(vector<vector<int>>& grid) { int m = grid.size(), n = grid[0].size(); vector<int> ii, jj; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j]) { ii.push_back(i); jj.push_back(j); } } } sort(jj.begin(), jj.end()); int c = ii.size(), s = 0, io = ii[c/2], jo = jj[c/2]; for (int i : ii) s += abs(i  io); for (int j : jj) s += abs(j  jo); return s; } };

You can see the second method: https://github.com/algorhythms/LeetCode/blob/master/296 Best Meeting Point.py