📜  二维二进制数组中的最佳交汇点

📅  最后修改于: 2021-05-05 01:39:21             🧑  作者: Mango

您将获得一个2D网格,其值为0或1,其中每个1表示组中某人的家。两个或两个以上的人希望见面并最大程度地缩短总行驶距离。他们可以在任何地方见面,这意味着可能没有家。

  • 使用曼哈顿距离计算距离,其中距离(p1,p2)= | p2.x – p1.x | + | p2.y – p1.y |。
  • 找到达到最佳集合点所需的总距离(总距离最小)。

例子:

Input : grid[][] = {{1, 0, 0, 0, 1}, 
                   {0, 0, 0, 0, 0},
                   {0, 0, 1, 0, 0}};
Output : 6
Best meeting point is (0, 2).
Total distance traveled is 2 + 2 + 2 = 6

Input : grid[3][5] = {{1, 0, 1, 0, 1},
                     {0, 1, 0, 0, 0}, 
                     {0, 1, 1, 0, 0}};
Output : 11

脚步 :-
1)存储所有组成员的所有水平和垂直位置。
2)现在将其排序以找到最小的中间位置,这将是最佳的交汇点。
3)找到所有成员与最佳集合点的距离。

例如,在上图中,水平位置为{0,2,0},垂直位置为{0,2,4}。对两者进行排序后,我们得到{0,0,2}和{0,2,4}。中间点是(0,2)。

注意:即使没有。的1有两个中间点,那么它也起作用。两个中间点意味着它总是有两个最佳会合点。两种情况将给出相同的距离。因此,我们将仅考虑一个最佳的交汇点以避免更多的开销,因为我们的目标是仅查找距离。

C++
/* C++ program to find best meeting point in 2D array*/
#include 
using namespace std;
#define ROW 3
#define COL 5
  
int minTotalDistance(int grid[][COL]) {
    if (ROW == 0 || COL == 0) 
         return 0;
      
    vector vertical;
    vector horizontal;
      
    // Find all members home's position 
    for (int i = 0; i < ROW; i++) {
        for (int j = 0; j < COL; j++) {
            if (grid[i][j] == 1) {
                vertical.push_back(i);
                horizontal.push_back(j);
            }
        }
    }
      
    // Sort positions so we can find most 
    // beneficial point
    sort(vertical.begin(),vertical.end());
    sort(horizontal.begin(),horizontal.end());
      
    // middle position will always beneficial 
    // for all group members but it will be
    // sorted which we have alredy done
    int size = vertical.size()/2;
    int x = vertical[size]; 
    int y = horizontal[size];
      
    // Now find total distance from best meeting 
    // point (x,y) using Manhattan Distance formula
    int distance = 0;
    for (int i = 0; i < ROW; i++) 
        for (int j = 0; j < COL; j++) 
            if (grid[i][j] == 1) 
                distance += abs(x - i) + abs(y - j);
      
    return distance;
}
  
// Driver program to test above functions
int main() {
    int grid[ROW][COL] = {{1, 0, 1, 0, 1}, {0, 1, 0, 0, 0},{0, 1, 1, 0, 0}};
    cout << minTotalDistance(grid);
    return 0;
}


Java
/* Java program to find best 
meeting point in 2D array*/
import java.util.*;
  
class GFG 
{
      
static int ROW = 3;
static int COL =5 ;
  
static int minTotalDistance(int grid[][])
{ 
    if (ROW == 0 || COL == 0) 
        return 0; 
      
    Vector vertical = new Vector(); 
    Vector horizontal = new Vector();
      
    // Find all members home's position 
    for (int i = 0; i < ROW; i++)
    { 
        for (int j = 0; j < COL; j++) 
        { 
            if (grid[i][j] == 1) 
            { 
                vertical.add(i); 
                horizontal.add(j); 
            } 
        } 
    } 
      
    // Sort positions so we can find most 
    // beneficial point 
    Collections.sort(vertical); 
    Collections.sort(horizontal); 
      
    // middle position will always beneficial 
    // for all group members but it will be 
    // sorted which we have alredy done 
    int size = vertical.size() / 2; 
    int x = vertical.get(size); 
    int y = horizontal.get(size); 
      
    // Now find total distance from best meeting 
    // point (x,y) using Manhattan Distance formula 
    int distance = 0; 
    for (int i = 0; i < ROW; i++) 
        for (int j = 0; j < COL; j++) 
            if (grid[i][j] == 1) 
                distance += Math.abs(x - i) +
                Math.abs(y - j); 
      
    return distance; 
} 
  
// Driver code
public static void main(String[] args) 
{
    int grid[][] = {{1, 0, 1, 0, 1}, 
                    {0, 1, 0, 0, 0},
                    {0, 1, 1, 0, 0}};
    System.out.println(minTotalDistance(grid));
}
} 
  
// This code is contributed by 29AjayKumar


Python3
# Python program to find best meeting point in 2D array
ROW = 3
COL = 5
  
def minTotalDistance(grid: list) -> int:
    if ROW == 0 or COL == 0:
        return 0
  
    vertical = []
    horizontal = []
  
    # Find all members home's position
    for i in range(ROW):
        for j in range(COL):
            if grid[i][j] == 1:
                vertical.append(i)
                horizontal.append(j)
  
    # Sort positions so we can find most
    # beneficial point
    vertical.sort()
    horizontal.sort()
  
    # middle position will always beneficial
    # for all group members but it will be
    # sorted which we have alredy done
    size = len(vertical) // 2
    x = vertical[size]
    y = horizontal[size]
  
    # Now find total distance from best meeting
    # point (x,y) using Manhattan Distance formula
    distance = 0
    for i in range(ROW):
        for j in range(COL):
            if grid[i][j] == 1:
                distance += abs(x - i) + abs(y - j)
  
    return distance
  
# Driver Code
if __name__ == "__main__":
  
    grid = [[1, 0, 1, 0, 1],
            [0, 1, 0, 0, 0], 
            [0, 1, 1, 0, 0]]
    print(minTotalDistance(grid))
  
# This code is contributed by
# sanjeev2552


C#
/* C# program to find best 
meeting point in 2D array*/
using System;
using System.Collections.Generic;
  
class GFG 
{
      
static int ROW = 3;
static int COL = 5 ;
  
static int minTotalDistance(int [,]grid)
{ 
    if (ROW == 0 || COL == 0) 
        return 0; 
      
    List vertical = new List(); 
    List horizontal = new List();
      
    // Find all members home's position 
    for (int i = 0; i < ROW; i++)
    { 
        for (int j = 0; j < COL; j++) 
        { 
            if (grid[i, j] == 1) 
            { 
                vertical.Add(i); 
                horizontal.Add(j); 
            } 
        } 
    } 
      
    // Sort positions so we can find most 
    // beneficial point 
    vertical.Sort(); 
    horizontal.Sort(); 
      
    // middle position will always beneficial 
    // for all group members but it will be 
    // sorted which we have alredy done 
    int size = vertical.Count / 2; 
    int x = vertical[size]; 
    int y = horizontal[size]; 
      
    // Now find total distance from best meeting 
    // point (x,y) using Manhattan Distance formula 
    int distance = 0; 
    for (int i = 0; i < ROW; i++) 
        for (int j = 0; j < COL; j++) 
            if (grid[i, j] == 1) 
                distance += Math.Abs(x - i) +
                Math.Abs(y - j); 
      
    return distance; 
} 
  
// Driver code
public static void Main(String[] args) 
{
    int [,]grid = {{1, 0, 1, 0, 1}, 
                    {0, 1, 0, 0, 0},
                    {0, 1, 1, 0, 0}};
    Console.WriteLine(minTotalDistance(grid));
}
} 
  
// This code is contributed by PrinciRaj1992


输出:

11

时间复杂度: O(M * N)
辅助空间: O(N)