Easy to understand java solution


  • 0
    H
    public class Solution {
        public int minTotalDistance(int[][] grid) {
            if (grid.length == 0) return 0;
            int count = 0;
            for (int i = 0; i < grid.length; i ++) {
                for (int j = 0; j < grid[0].length; j++) {
                    if (grid[i][j] == 1) {
                        count++;
                    }
                }
            }
            int[] xIndex = new int[count];
            int[] yIndex = new int[count];
            int x = 0, y = 0;
            for (int i = 0; i < grid.length; i++) {
                for (int j = 0; j < grid[0].length; j++) {
                    if (grid[i][j] == 1) {
                        xIndex[x++] = i;
                        yIndex[y++] = j;
                    }
                }
            }
            Arrays.sort(xIndex);
            Arrays.sort(yIndex);
            return helper(xIndex, 0, count - 1) + helper(yIndex, 0, count - 1);
        }
        public int helper(int[] grid, int i, int j) {
            int res = 0;
            while (j - i > 0) {
                res += grid[j] - grid[i];
                j--;
                i++;
            }
            return res;
        }
    }

Log in to reply
 

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