A Group of people wants to meet and minimize the total travel distance. You is given a 2D grid of values 0 or 1, where each 1 marks the home of someone in the group. The distance is calculated using Manhattan distance, where distance (P1, p2) = |p2.x - p1.x| + |p2.y - p1.y|
.
For example, given three people living at (0,0)
,, (0,4)
and (2,2)
:
1 |
0 |
0 |
0 |
1 |
0 |
0 |
0 |
0 |
0 |
0 |
0 |
1 |
0 |
0 |
The point (0,2)
is a ideal meeting point, as the all travel distance of 2+2+2=6 is minimal. So return 6.
Solution 1. Median in Math. Collect coordinates in sorted order.
1 Public classSolution {2 Public intMintotaldistance (int[] grid) {3 intm = grid.length, n = grid[0].length;4 intTotal = 0, z[] =New int[m*n];5 for(intdim=0; dim<2; ++Dim) {6 inti = 0, j = 0;7 if(Dim = = 0) {8 for(intx=0; x<n; ++x)9 for(inty=0; y<m; ++y)Ten if(Grid[y][x] = = 1) OneZ[j++] =x; A}Else { - for(inty=0; y<m; ++y) - for(intG:grid[y]) the if(g = = 1) -Z[j++] =y; - } - while(I <--j) +Total + = Z[j]-z[i++]; - } + returnTotal ; A } at}
Solution 2. Count How many people live with each row and each column. Only O (m+n) space.
1 Public classSolution {2 Public intMintotaldistance (int[] grid) {3 intm = grid.length, n = grid[0].length;4 int[] I =New int[M], J =New int[n];5 for(inti=0; i<m; ++i)6 for(intj=0; j<n; ++j)7 if(Grid[i][j] = = 1) {8++I[i];9++J[j];Ten } One A intTotal = 0; - for(int[] K:New int[][]{I, J}] { - inti = 0, j = k.length-1; the while(I <j) { - intK =math.min (K[i], k[j]); -Total + = k * (J-i); - if((k[i]-= K) = = 0) + +i; + if((k[j]-= K) = = 0)--J; - } + } A returnTotal ; at } -}
296. Best meeting Point