# 3-Line Python Solution

• ``````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])``````

• 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;
}
}; ``````

• the ii array does not need to be sorted.

• yeah, u r right

• Oh, thanks for your remind!

• Would you give a few explanation on this piece of code? What's the idea behind it?

• Thank you so much!

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.