C++ easy to understand solution.

  • 0
    int minTotalDistance(vector<vector<int>>& grid) {
        if (grid.empty())
            return 0;
        vector<int> row, col;
        for (int i=0; i<grid.size(); i++)
            for (int j=0; j<grid[0].size(); j++) {
                if (grid[i][j]) {
        sort(col.begin(), col.end());
        vector<int>::iterator mid_row = row.begin()+row.size()/2;
        vector<int>::iterator mid_col = col.begin()+col.size()/2;
        int res = 0;
        for (auto r: row)
            res += abs(r-*mid_row);
        for (vector<int>::iterator it=col.begin(); it!=col.end();it++)
            res += *it>*mid_col?*it-*mid_col:*mid_col-*it;
        return res;

Log in to reply

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