Sharing my 20ms C++ solution


  • 0
    T
    class Solution {
    public:
        int minTotalDistance(vector<vector<int>>& grid) {
            int m = grid.size();
            if(m==0)
                return 0;
            int n = grid[0].size();
            if(n==0)
                return 0;
                
            int i, j;
            vector<int> rowPos;
            vector<int> colPos;
            for(i=0; i<m; i++)
                for(j=0; j<n; j++)
                    if(grid[i][j]==1)
                    {
                        rowPos.push_back(i);
                        colPos.push_back(j);
                    }
                    
            sort(rowPos.begin(), rowPos.end());
            sort(colPos.begin(), colPos.end());
            if(rowPos.size()==0)
                return 0;
            int middleRow = rowPos[rowPos.size()/2];
            int middleCol = colPos[colPos.size()/2];
            
            int result = 0;
            for(i=0; i<rowPos.size(); i++)
                result += abs(rowPos[i]-middleRow);
            for(i=0; i<colPos.size(); i++)
                result += abs(colPos[i]-middleCol);
                
            return result;
        }
    };

Log in to reply
 

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