def minTotalDistance(self, grid):
if not grid:
return 0
r, c = len(grid), len(grid[0])
sumr = [i for i in xrange(r) for j in xrange(c) if grid[i][j]]
sumc = [j for i in xrange(r) for j in xrange(c) if grid[i][j]]
sumr.sort()
sumc.sort()
mid_row = sumr[len(sumr)/2]
mid_col = sumc[len(sumc)/2]
return sum([abs(rmid_row) for r in sumr]) + sum([abs(cmid_col) for c in sumc])
Python easy to understand solution.


same idea but mine is somewhat ugly...
def minTotalDistance(self, grid): [x, y] = map(sorted, zip(*[ (i, j) for i, row in enumerate(grid)\ for j, ele in enumerate(row) if ele])) l = len(x) return sum(x[l/2+1:])  sum(x[:l/2]) + (1  (l & 1)) * (x[l/2]) + \ sum(y[l/2+1:])  sum(y[:l/2]) + (1  (l & 1)) * (y[l/2])