Best meeting point in 2D binary array
Last Updated :
18 Jul, 2022
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 :-
- Store all horizontal and vertical positions of all group member.
- Now sort it to find minimum middle position, which will be the best meeting point.
- 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
<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>
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
Find the Peak Element in a 2D Array/Matrix Given a 2D Array/Matrix mat[][], the task is to find the Peak element.An element is a peak element if it is greater than or equal to its four neighbors, left, right, top and bottom. A peak element is not necessarily the overall maximal element. It only needs to be greater than existing adjacent More
12 min read
Nearest 1 in a binary matrix Given a binary grid of n*m. Find the distance of the nearest 1 in the grid for each cell. The distance is calculated as |i1 - i2| + |j1 - j2|, where i1, j1 are the row number and column number of the current cell, and i2, j2 are the row number and column number of the nearest cell having value 1. T
15+ min read
Find an element in Bitonic array Given a bitonic sequence of n distinct elements, and an integer x, the task is to write a program to find given element x in the bitonic sequence in O(log n) time. A Bitonic Sequence is a sequence of numbers that is first strictly increasing then after a point decreasing. Examples: Input : arr[] = {
11 min read
Emulating a 2-d array using 1-d array How to convert a 2-d array of size (m x n) into 1-d array and how to store the element at position [i, j] of 2-d array in 1-d array? Clearly, the size of 1-d array is the number of elements in 2-d array i.e. m x n). If the elements in the 2-d array are stored in row-major order. Then, the element at
5 min read
Range Update Queries to XOR with 1 in a Binary Array. Given a binary array arr[] of size N. The task is to answer Q queries which can be of any one type from below: Type 1 - 1 l r : Performs bitwise xor operation on all the array elements from l to r with 1. Type 2 - 2 l r : Returns the minimum distance between two elements with value 1 in a subarray [
15+ min read
Bitonic Point - Maximum in Increasing Decreasing Array Given an array arr[] of integers which is initially strictly increasing and then strictly decreasing, the task is to find the bitonic point, that is the maximum value in the array. Note: Bitonic Point is a point in bitonic sequence before which elements are strictly increasing and after which elemen
10 min read
Maximum distance between two 1s in a Binary Array in a given range Given a binary array of size N and a range in [l, r], the task is to find the maximum distance between two 1s in this given range.Examples: Input: arr = {1, 0, 0, 1}, l = 0, r = 3 Output: 3 In the given range from 0 to 3, first 1 lies at index 0 and last at index 3. Hence, maximum distance = 3 - 0 =
14 min read
Find the Best Sightseeing Pair Given an integer array arr[] where arr[i] represents the value of the ith sightseeing spot. Two sightseeing spots i and j have a distance j - i between them. The score of a pair (i < j) of sightseeing spots is arr[i] + arr[j] + i - j: the sum of arr[]of the sightseeing spots, minus the distance b
5 min read
Create a Sorted Array Using Binary Search Given an array, the task is to create a new sorted array in ascending order from the elements of the given array.Examples: Input : arr[] = {2, 5, 4, 9, 8} Output : 2 4 5 8 9 Input : arr[] = {10, 45, 98, 35, 45} Output : 10 35 45 45 98 The above problem can be solved efficiently using Binary Search.
9 min read
Binary Array Range Queries to find the minimum distance between two Zeros Prerequisite: Segment TreesGiven a binary array arr[] consisting of only 0's and 1's and a 2D array Q[][] consisting of K queries, the task is to find the minimum distance between two 0's in the range [L, R] of the array for every query {L, R}. Examples: Input: arr[] = {1, 0, 0, 1}, Q[][] = {{0, 2}}
14 min read