# Best meeting point in 2D binary array in C++

In this problem, we are given a 2D binary array i.e. it has values that are either 0 or 1, where 1 is marked as a home of a person of the group. And people of the group want to meet. So, they need to minimise the total distance travelled by them for meeting at a common point. A valid meeting point can be anywhere but not at anyone home.

For find minimum distance a formula is created, this is named as manhattan distance, where distance −

(p1, p2) = |p2.x| + |p2.y - p1.y|.

Let’s take an example, to make the concept clear

## Example

Input:
{10001}
{00000}
{00100}
Output: 6

Explanation − Here the best meeting point is (0,2 ) which make the distance travelled equal to 6 (2+2+2).

Now, lets create a solution for this problem. Here, we have to find a middle point from all the points marked as 1 in the array. we will do this by finding horizontal and vertical centres( middle points) separately. and I'm finding the distance of the point from all the 1 marked points.

## ALGORITHM

Step 1 : Create two structures with the values of horizontal and vertical positions of the points Marked one.
Step 2 : In both this structures, find the mid positions and treat (midx, midy) it as the meeting point.
Step 3 : Calculate the distance of each point it to the mid. Step 4 : return the sum of all distances.

## Example

Let’s create an algorithm based on this algorithm −

#include <bits/stdc++.h>
using namespace std;
#define ROW 3
#define COL 5
int minMeetingDistance(int grid[][COL]) {
if (ROW == 0 || COL == 0)
return 0;
vector<int> vertical;
vector<int> horizontal;
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(vertical.begin(),vertical.end());
sort(horizontal.begin(),horizontal.end());
int size = vertical.size()/2;
int midx = vertical[size];
int midy = horizontal[size];
int distance = 0;
for (int i = 0; i < ROW; i++)
for (int j = 0; j < COL; j++)
if (grid[i][j] == 1)
distance += abs(midx - i) + abs(midy - j);
return distance;
}
int main() {
int distance[ROW][COL] =
{{1, 0, 1, 0, 1},
{0, 0, 0, 1, 0},
{0, 1, 1, 0, 0}};
cout<<"The minimum distance travelled to meet is "<<minMeetingDistance(distance);
return 0;
}

## Output

The minimum distance travelled to meet is 11