Best meeting point in 2D binary array | C # program to find best meeting point in 2D array ; Find all members home 's position ; Sort positions so we can find most beneficial point ; middle position will always beneficial for all group members but it will be sorted which we have already done ; Now find total distance from best meeting point ( x , y ) using Manhattan Distance formula ; Driver code
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 > ( ) ; 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 ) ; } } } vertical . Sort ( ) ; horizontal . Sort ( ) ; int size = vertical . Count / 2 ; int x = vertical [ size ] ; int y = 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 += Math . Abs ( x - i ) + Math . Abs ( y - j ) ; return distance ; } 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 ) ) ; } }