Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Best meeting point in 2D binary array

  • Difficulty Level : Medium
  • Last Updated : 03 Sep, 2021

You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in a group. And the group of two or more people wants to meet and minimize the total travel distance. They can meet anywhere means that there might be a home or not.
 

  • The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x – p1.x| + |p2.y – p1.y|.
  • Find the total distance that needs to be traveled to reach the best meeting point (Total distance traveled is minimum).

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.



Examples: 
 

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

 

Steps :- 
1) Store all horizontal and vertical positions of all group member. 
2) Now sort it to find minimum middle position, which will be the best meeting point. 
3) Find the distance of all members from best meeting point.
For example in above diagram, horizontal positions are {0, 2, 0} and vertical positions are {0, 2, 4}. After sorting both, we get {0, 0, 2} and {0, 2, 4}. Middle point is (0, 2).
Note : Even no. of 1’s have two middle points, then also it works. Two middle points means it have two best meeting points always. Both cases will give same distance. So we will consider only one best meeting point to avoid the more overhead, Because our aim is to find the distance only. 
 

C++




/* C++ program to find best meeting point in 2D array*/
#include <bits/stdc++.h>
using namespace std;
#define ROW 3
#define COL 5
 
int minTotalDistance(int grid[][COL]) {
    if (ROW == 0 || COL == 0)
         return 0;
     
    vector<int> vertical;
    vector<int> 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 already 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<Integer> vertical = new Vector<Integer>();
    Vector<Integer> horizontal = new Vector<Integer>();
     
    // 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 already 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 already 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<int> vertical = new List<int>();
    List<int> horizontal = new List<int>();
     
    // 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 already 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

Javascript




<script>
/* Javascript program to find best
meeting point in 2D array*/
 
let ROW = 3;
let COL =5 ;
 
function minTotalDistance(grid)
{
    if (ROW == 0 || COL == 0)
        return 0;
       
    let vertical = [];
    let horizontal = [];
       
    // Find all members home's position
    for (let i = 0; i < ROW; i++)
    {
        for (let j = 0; j < COL; j++)
        {
            if (grid[i][j] == 1)
            {
                vertical.push(i);
                horizontal.push(j);
            }
        }
    }
       
    // Sort positions so we can find most
    // beneficial point
    (vertical).sort(function(a,b){return a-b;});
    (horizontal).sort(function(a,b){return a-b;});
       
    // middle position will always beneficial
    // for all group members but it will be
    // sorted which we have already done
    let size = vertical.length / 2;
    let x = vertical[size];
    let y = horizontal[size];
       
    // Now find total distance from best meeting
    // point (x,y) using Manhattan Distance formula
    let distance = 0;
    for (let i = 0; i < ROW; i++)
        for (let j = 0; j < COL; j++)
            if (grid[i][j] == 1)
                distance += Math.abs(x - i) +
                Math.abs(y - j);
       
    return distance;
}
 
// Driver code
let grid = [[1, 0, 1, 0, 1],
                    [0, 1, 0, 0, 0],
                    [0, 1, 1, 0, 0]];
document.write(minTotalDistance(grid));
 
 
// This code is contributed by rag2127
</script>

Output: 
 

11

Time Complexity : O(M*N) 
Auxiliary Space : O(N) 
This article is contributed by Harshit Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :