The Wayback Machine - https://web.archive.org/web/20241008191748/https://www.geeksforgeeks.org/best-meeting-point-2d-binary-array/
Open In App

Best meeting point in 2D binary array

Last Updated : 18 Jul, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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).

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

Concept :-

Let the group of people be present at the coordinates G : (Gx, Gy), H : (Hx, Hy), J : (Jx, Jy), and K : (Kx, Ky).

Let the Best Meeting Point be P : (x, y)

Distance of every point from P will be given by,

D = |Gx - x| + |Gy - y| + |Hx - x| + |Hy - y| + |Jx - x| + |Jy - y| + |Kx - x| + |Ky - y|

which can also be written as,

D = Dx + Dy
where, Dx  =  |Gx - x|  + |Hx - x| + |Jx - x|  + |Kx - x| 
  and, Dy = |Gy - y| + |Hy - y| + |Jy - y| + |Ky - y|

To minimize D, we should minimize Dx and Dy.

Dx will be minimum if x is the median of (Gx, Hx, Jx, Kx) 
and Similarly, Dy will be minimum if y is the median of (Gy, Hy, Jy, Ky)

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. 

Implementation:

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 minTotalDistance(int grid[][],int ROW , int COL)
{
    if (ROW == 0 || COL == 0)
        return 0;
     
    List<Integer> vertical = new ArrayList<>();
    List<Integer> horizontal = new ArrayList<>();
     
    // 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 , grid.length , grid[0].length));
}
}
 
// 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





Output

11

In worst case if all the elements of Matrix are set to 1. Then we would have to sort N*M elements. Time to sort is (N*M)log(N*M) or 2N^2log(N)

Time Complexity : O(M*N) 
Auxiliary Space : O(N) 

 



Similar Reads

Number of Distinct Meeting Points on a Circular Road
Consider two cars A and B, running infinitely (either clockwise or anti-clockwise) on a circular road. Given the speed of both the cars a and b. If a or b is positive, indicate they are moving in clockwise, Else they are moving in the anti-clockwise direction. The task is to find the number of distinct points they will meet each other at.Examples:
6 min read
Count intervals that intersects with a given meeting time
Given an array arr[][2] consisting of N pair of strings representing the starting and ending time (in 12 hours format) and a string P which represents the time of the meeting, the task is to find the count of intervals that contains the time P. Examples: Input: P = “12:01:AM”, arr[][2] = {{“12:00:AM”, “11:55:PM”}, {“12:01:AM”, “11:50:AM”}, {“12:30:
9 min read
Find maximum number of people who can attend meeting
There is only one room which is holding N meetings that are given as intervals of the form (start[i], end[i], people[i]) where start[i] is the starting time of the ith meeting, end[i] is the ending time of the ith meeting, people[i] is the number of people who can attend the ith meeting. At any point of time, the room can be occupied by only one me
12 min read
Meeting Scheduler for Two Persons
You have given the availability time slots 'slots1' and 'slots2' of two people and a meeting duration 'd', for any i, slots[i] = {starti , endi}. return the earliest time slot that works for both of them and is of 'd' duration. If there is no common time slot that satisfies the requirements, return an empty array. It is guaranteed that no two avail
6 min read
Meeting Rooms - Check if a person can attend all meetings
Given an array arr[][] such that arr[i][0] is the starting time of ith meeting and arr[i][1] is the ending time of ith meeting, the task is to check if it is possible for a person to attend all the meetings such that he can attend only one meeting at a particular time. Note: A person can also attend a meeting if it's starting time is same as the pr
10 min read
Reflection of a point at 180 degree rotation of another point
Given two points coordinates (x1, y1) and (x2, y2)on 2D plane. The task is to find the reflection of (x1, y1) at 180 degree rotation of (x2, y2).Examples: Input : x1 = 0, y1 = 0, x2 = 1, y2 = 1 Output : (2, 2) Input : x1 = 1, y1 = 1, x2 = 2, y2 = 2 Output : (3, 3) Let the reflection point of point (x1, y1) about (x2, y2) be (x', y'). For (x', y') b
4 min read
Find time required to reach point N from point 0 according to given rules
Given two positive integers X and Y and N number of points arranged in a line, the task is to find the time required to reach point N from point 0 according to the following rules: Every point has one barrier that closes after every Y minutes and remains closed for the next Y minutes.On reaching a point if the barrier is closed, then the person nee
7 min read
Rotation of a point about another point
We have already discussed the rotation of a point P about the origin in the Set 1 and Set 2. The rotation of point P about origin with an angle ? in the anti-clockwise direction is given as under: Rotation of P about origin: P * polar(1.0, ?)Rotation of P about point Q Now, we have to rotate the point P not about origin but about a general point Q.
8 min read
Find the transition point in a binary array
Given a sorted array containing only numbers 0 and 1, the task is to find the transition point efficiently. The transition point is the point where "0" ends and "1" begins. Examples : Input: 0 0 0 1 1 Output: 3 Explanation: Index of first 1 is 3 Input: 0 0 0 0 1 1 1 1 Output: 4 Explanation: Index of first 1 is 4Recommended PracticeFind Transition P
10 min read
Unbounded Binary Search Example (Find the point where a monotonically increasing function becomes positive first time)
Given a function 'int f(unsigned int x)' which takes a non-negative integer 'x' as input and returns an integer as output. The function is monotonically increasing with respect to the value of x, i.e., the value of f(x+1) is greater than f(x) for every input x. Find the value 'n' where f() becomes positive for the first time. Since f() is monotonic
11 min read
Exit Point in a Binary Matrix
Given a binary matrix of size N x M, you enter the matrix at cell (0, 0) in the left to the right direction. Whenever encountering a 0 retain in the same direction if encountered a 1 change direction to the right of the current direction and change that 1 value to 0, find out exit point from the Matrix. Examples: Input: matrix = {{0, 1, 0}, {0, 1,
8 min read
Generate all binary permutations such that there are more or equal 1's than 0's before every point in all permutations
Generate all permutations of a given length such that every permutation has more or equals 1's than 0's in all prefixes of the permutation. Examples: Input: len = 4 Output: 1111 1110 1101 1100 1011 1010 Note that a permutation like 0101 can not be in output because there are more 0's from index 0 to 2 in this permutation. Input: len = 3 Output: 111
5 min read
Binary Search for Rational Numbers without using floating point arithmetic
A rational is represented as p/qb, for example 2/3. Given a sorted array of rational numbers, how to search an element using Binary Search. Use of floating-point arithmetic is not allowed. Example: Input: arr[] = {1/5, 2/3, 3/2, 13/2} x = 3/2 Output: Found at index 2 We strongly recommend you to minimize your browser and try this yourself first.To
9 min read
Binary Indexed Tree : Range Updates and Point Queries
Given an array arr[0..n-1]. The following operations need to be performed. update(l, r, val): Add ‘val’ to all the elements in the array from [l, r].getElement(i): Find element in the array indexed at ‘i’. Initially all the elements in the array are 0. Queries can be in any order, i.e., there can be many updates before point query. Example: Input:
15+ min read
Leaf starting point in a Binary Heap data structure
Binary Heap is a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). In other words, we can say that it's an almost complete binary tree. A Binary heap is typically represented as array. If we take a closer look, we can noticed that in a Heap with number of nodes n, th
2 min read
Find a partition point in array to maximize its xor sum
Given an array a of size N. The task is to find an index 'i' (1 <= i <= N) such that (a[1] ^ ... ^ a[i]) + (a[i+1] ^ ... ^ a[N]) (x^y represents the xor value of x and y) is maximum possible. Examples: Input : arr[] = {1, 4, 6, 3, 8, 13, 34, 2, 21, 10} Output : 2 Explanation : The maximum value is 68 at index 2 Input : arr[] = {1, 2, 3, 4, 5,
12 min read
Sort an Array of Points by their distance from a reference Point
Given an array arr[] containing N points and a reference point P, the task is to sort these points according to their distance from the given point P. Examples: Input: arr[] = {{5, 0}, {4, 0}, {3, 0}, {2, 0}, {1, 0}}, P = (0, 0) Output: (1, 0) (2, 0) (3, 0) (4, 0) (5, 0) Explanation: Distance between (0, 0) and (1, 0) = 1 Distance between (0, 0) an
7 min read
Maximum Fixed Point (Value equal to index) in a given Array
Given an array arr[] of size N, the task is to find the maximum index i such that arr[i] is equal to i. If there is no such index in the array arr[] then print -1. Examples: Input: arr[ ] = {-10, -5, 0, 3, 7}Output: 3Explanation: Only for i=3, arr[3] = 3 Input: arr[ ] = {0, 2, 5, 8, 4}Output: 4 Approach: Follow the steps below to solve this problem
4 min read
Make N pairs from Array as (X, Y) coordinate point that are enclosed inside a minimum area rectangle
Given a number N, and an array A[] of size 2N, the task is to make N pairs of these array elements and place them on an X-Y coordinate plane, such that they are enclosed inside a minimum area rectangle( with sides parallel to the X-axis and Y-axis) and print the area of the rectangle. Examples: Input: N = 4, A = {1, 4, 2, 5, 3, 6, 7, 8}Output: 9Exp
7 min read
Check if it is possible to reach the point (X, Y) using distances given in an array
Given an array arr[] consisting of N positive integers and two integers X and Y, the task is to check if it is possible to reach (X, Y) from (0, 0) such that moving to (Xf, Yf) from (Xi, Yi) is allowed only if the euclidean distance between them is present in the array arr[]. If it is possible, then print Yes. Otherwise, print No. Note: Each distan
7 min read
Maximize point to reduce Array by replacing Subarray with its sum
Given an array arr[] of size, N, the task is to maximize the score to reduce the array to a single element by replacing any subarray with its sum where the score of one such operation is the product of subarray length and the minimum value of that subarray. Examples:Input: N = 2, arr[] = {1, 5}Output: 2Explanation: Select subarray (0, 1). Then arra
15 min read
Find a Fixed Point (Value equal to index) in a given array | Duplicates Allowed
Given an array of n integers sorted in ascending order, write a function that returns a Fixed Point in the array, if there is any Fixed Point present in the array, else returns -1. Fixed Point in an array is an index i such that arr[i] is equal to i. Note that integers in the array can be negative. Examples: Input: arr[] = {-10, -5, 0, 3, 7} Output
13 min read
Find Equal (or Middle) Point in a sorted array with duplicates
Given a sorted array of n size, the task is to find whether an element exists in the array from where the number of smaller elements is equal to the number of greater elements.If Equal Point appears multiple times in input array, return the index of its first occurrence. If doesn't exist, return -1. Examples : Input : arr[] = {1, 2, 3, 3, 3, 3} Out
9 min read
Find a partition point in array
Given an unsorted array of integers. Find an element such that all the elements to its left are smaller and to its right are greater. Print -1 if no such element exists. Note that there can be more than one such elements. For example an array which is sorted in increasing order all elements follow the property. We need to find only one such element
15 min read
Find a Fixed Point in an array with duplicates allowed
Given an array of n duplicates or distinct integers sorted in ascending order, write a function that returns a Fixed Point in the array, if there is any Fixed Point present in the array, else returns -1. Fixed Point in an array is an index i such that arr[i] is equal to i. Note that integers in the array can be negative. Examples : Input : arr[] =
8 min read
Find a Fixed Point (Value equal to index) in a given array
Given an array of n distinct integers sorted in ascending order, write a function that returns a Fixed Point in the array, if there is any Fixed Point present in the array, it returns -1. Fixed Point in an array is an index i such that arr[i] equals i. Note that integers in the array can be negative. Examples: Input: arr[] = {-10, -5, 0, 3, 7}Outpu
9 min read
Find the occurrence of the given binary pattern in the binary representation of the array elements
Given an array arr[] of N positive integers and a string patt which consists of characters from the set {0, 1}, the task is to find the count occurrence of patt in the binary representation of every integer from the given array. Examples: Input: arr[] = {5, 106, 7, 8}, patt = "10" Output: 1 3 0 1 binary(5) = 101 -> occurrence(10) = 1 binary(106)
9 min read
Count ways of creating Binary Array ending with 1 using Binary operators
Given an array of characters arr[] of size N, whose each character is either '&' (Bitwise AND) or '|' (Bitwise OR). there are many possible ways of having a binary array of size N+1. Any of these arrays (say X[]) is transformed to another array Y[] by performing the following operations Y[0] = X[0].for every i ( i from 1 to N-1) Y[i] = (Y[i - 1
15+ min read
Check if it is possible to go from one point to another by choosing a Subsequence of steps of smallest length
Given a string S of characters R, L, U, D, along with integers X1, Y1, X2, Y2. In String S, 'R', 'L', 'U', and'D' denote right, left, up, and down steps from the current position. Then the task is to output the length of the smallest length subsequence of steps from S, such that following those steps we can reach from (X1, Y1) to (X2, Y2). If it is
9 min read
Program to find the mid-point of a line
Given two coordinates of a line starting is (x1,y1) and ending is (x2,y2) find out the mid-point of a line. Examples : Input : x1 = –1, y1 = 2, x2 = 3, y2 = –6 Output : 1,–2 Input : x1 = 6.4, y1 = 3 x2 = –10.7, y2 = 4 Output : –2.15, 3.5 The Midpoint Formula: The midpoint of two points, (x1, y2) and (x2, y2) is the point M found by the following fo
3 min read
Article Tags :
Practice Tags :