public int minTotalDistance(int[][] grid) {
        if (grid == null) return 0;

        ArrayList<Integer> xs = new ArrayList<Integer>();
        ArrayList<Integer> ys = new ArrayList<Integer>();
        for (int i = 0; i < grid.length; ++i) {
            for (int j = 0; j < grid[0].length; ++j) {
                if (grid[i][j] == 1) {
                    xs.add(i);
                    ys.add(j);
                }
            }
        }
        // actually no need to sort xs since it's already in order
        Collections.sort(ys);
        return getMinDistance(xs) + getMinDistance(ys);
    }