Share my C++ solution


  • 0
    O
    int minTotalDistance(vector<vector<int>>& grid) {
        int n = grid.size();
        if (n <= 0) {
            return 0;
        }
        int m = grid[0].size();
        if (m <= 0) {
            return 0;
        }
        vector<int> rows, cols;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j]) {
                    rows.push_back(i);
                    cols.push_back(j);
                }
            }
        }
        
        sort(cols.begin(), cols.end());
        
        int row_mid = rows[rows.size() / 2];
        int col_mid = cols[cols.size() / 2];
        
        int dist = 0;
        for (auto i : rows) {
            dist += abs(i - row_mid);
        }
        for (auto j : cols) {
            dist += abs(j - col_mid);
        }
        return dist;
    }

Log in to reply
 

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