Python easy to understand solution.


  • 3
    C
    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(r-mid_row) for r in sumr]) + sum([abs(c-mid_col) for c in sumc])

  • 0

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

  • 0

    Sorting is unnecessary. You use two loops to get coordinates and they will be in order naturally.


Log in to reply
 

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