问题描述:
有一队人(两人或以上)想要在一个地方碰面,他们希望能够最小化他们的总行走距离。给你一个 2D 网格,其中各个格子内的值要么是 0,要么是 1。 1表示某个人的家所处的位置。
原因分析:
public class 最佳碰头地点 {
public static int minTotalDistance(int[][] grid){
int N = grid.length;
int M = grid[0].length;
int[] iOnes = new int[N];//统计每一行有多少1
int[] jOnes = new int[M];//统计每一列有多少1
for(int i =0;i<N;i++){
for(int j =0;j<M;j++){
if(grid[i][j] == 1){
iOnes[i]++;
jOnes[j]++;
}
}
}
//找到最少行走距离所在行
int total = 0;
int i = 0;
int j = N-1;
int iRest = 0;
int jRest = 0;
while(i < j){
if(iOnes[i] + iRest <=iOnes[j] + jRest){
total += iOnes[i] + iRest;
iRest += iOnes[i++];
}else{
total += iOnes[j] + jRest;
jRest += iOnes[j--];
}
}
//找到最少行走距离所在列
i = 0;
j = M-1;
iRest = 0;
jRest = 0;
while(i < j){
if(jOnes[i] + iRest <= jOnes[j] + jRest){
total += jOnes[i] + iRest;
iRest +=jOnes[i++];
}else{
total += jOnes[j] + jRest;
jRest +=jOnes[j--];
}
}
return total;
}
}