• Time:O(mn)
• Space:O(mn)

## C++

``````class Solution {
public:
int minTotalDistance(vector<vector<int>>& grid) {
const int m = grid.size();
const int n = grid[0].size();
vector<int> I;  // i indices s.t. grid[i][j] == 1
vector<int> J;  // j indices s.t. grid[i][j] == 1

for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (grid[i][j])
I.push_back(i);

for (int j = 0; j < n; ++j)
for (int i = 0; i < m; ++i)
if (grid[i][j])
J.push_back(j);

// sum(i - median(I)) + sum(j - median(J))
return minTotalDistance(I) + minTotalDistance(J);
}

private:
int minTotalDistance(const vector<int>& grid) {
int sum = 0;
int i = 0;
int j = grid.size() - 1;

while (i < j)
sum += grid[j--] - grid[i++];

return sum;
}
};
``````

## JAVA

``````class Solution {
public int minTotalDistance(int[][] grid) {
final int m = grid.length;
final int n = grid[0].length;
List<Integer> I = new ArrayList<>(); // i indices s.t. grid[i][j] == 1
List<Integer> J = new ArrayList<>(); // j indices s.t. grid[i][j] == 1

for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (grid[i][j] == 1)

for (int j = 0; j < n; ++j)
for (int i = 0; i < m; ++i)
if (grid[i][j] == 1)

// sum(i - median(I)) + sum(j - median(J))
return minTotalDistance(I) + minTotalDistance(J);
}

private int minTotalDistance(List<Integer> grid) {
int sum = 0;
int i = 0;
int j = grid.size() - 1;

while (i < j)
sum += grid.get(j--) - grid.get(i++);

return sum;
}
}
``````

## Python

``````class Solution:
def minTotalDistance(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
# i indices s.t. grid[i][j] == 1
I = [i for i in range(m) for j in range(n) if grid[i][j]]
# j indices s.t. grid[i][j] == 1
J = [j for j in range(n) for i in range(m) if grid[i][j]]

def minTotalDistance(grid: List[int]) -> int:
summ = 0
i = 0
j = len(grid) - 1

while i < j:
summ += grid[j] - grid[i]
i += 1
j -= 1

return summ

# sum(i - median(I)) + sum(j - median(J))
return minTotalDistance(I) + minTotalDistance(J)
``````