Best meeting point in 2D binary array | Javascript 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
let ROW = 3 ; let COL = 5 ; function minTotalDistance ( grid ) { if ( ROW == 0 COL == 0 ) return 0 ; let vertical = [ ] ; let horizontal = [ ] ; 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 ) ; } } } ( vertical ) . sort ( function ( a , b ) { return a - b ; } ) ; ( horizontal ) . sort ( function ( a , b ) { return a - b ; } ) ; let size = vertical . length / 2 ; let x = vertical [ size ] ; let y = horizontal [ size ] ; 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 ; } let grid = [ [ 1 , 0 , 1 , 0 , 1 ] , [ 0 , 1 , 0 , 0 , 0 ] , [ 0 , 1 , 1 , 0 , 0 ] ] ; document . write ( minTotalDistance ( grid ) ) ;