Best Meeting Point in C++

C++Server Side ProgrammingProgramming

Suppose there is a group of two or more people and they wants to meet and minimize the total travel distance. We have a 2D grid of values 0 or 1, where each 1 mark the home of someone in the group. The distance is calculated using the formula of Manhattan Distance, so distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.

So, if the input is like

10001
00000
00100

then the output will be 6 as from the matrix we can understand that three people living at (0,0), (0,4), and (2,2): The point (0,2) is an ideal meeting point, as the total travel distance of 2+2+2=6 is minimum.

To solve this, we will follow these steps −

  • Define a function get(), this will take an array v,

  • sort the array v

  • i := 0

  • j := size of v

  • ret := 0

  • while i < j, do −

    • ret := ret + v[j] - v[i]

    • (increase i by 1)

    • (decrease j by 1)

  • return ret

  • From the main method do the following −

  • Define an array row

  • Define an array col

  • for initialize i := 0, when i < size of grid, update (increase i by 1), do −

    • for initialize j := 0, when j < size of grid[0], update (increase j by 1), do −

      • if grid[i, j] is non-zero, then −

        • insert i at the end of row

        • insert j at the end of col

  • return get(row) + get(col)

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int minTotalDistance(vector<vector<int>>& grid) {
      vector<int> row;
      vector<int> col;
      for (int i = 0; i < grid.size(); i++) {
         for (int j = 0; j < grid[0].size(); j++) {
            if (grid[i][j]) {
               row.push_back(i);
               col.push_back(j);
            }
         }
      }
      return get(row) + get(col);
   }
   int get(vector <int> v){
      sort(v.begin(), v.end());
      int i = 0;
      int j = v.size() - 1;
      int ret = 0;
      while (i < j) {
         ret += v[j] - v[i];
         i++;
         j--;
      }
      return ret;
   }
};
main(){
   Solution ob;
   vector<vector<int>> v = {{1,0,0,0,1},{0,0,0,0,0},{0,0,1,0,0}};
   cout << (ob.minTotalDistance(v));
}

Input

{{1,0,0,0,1},{0,0,0,0,0},{0,0,1,0,0}}

Output

6
raja
Updated on 21-Jul-2020 08:05:42

Advertisements