```
public int minTotalDistance(int[][] grid) {
return minDistance(grid, 0) + minDistance(grid, 1);
}
private int minDistance(int[][] grid, int dim) {
int m = grid.length;
int n = grid[0].length;
int total = 0;
List<Integer> Z = new ArrayList<>();
if (dim == 0) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
Z.add(i);
}
}
}
} else { // dim == 1
for (int j = 0; j < n; j++) {
for (int i = 0; i < m; i++) {
if (grid[i][j] == 1) {
Z.add(j);
}
}
}
}
int lo = 0, hi = Z.size() - 1;
while (lo < hi) {
total += Z.get(hi--) - Z.get(lo++);
}
return total;
}
```