Best meeting point in 2D binary array | Python 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
ROW = 3 NEW_LINE COL = 5 NEW_LINE def minTotalDistance ( grid : list ) -> int : NEW_LINE INDENT if ROW == 0 or COL == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT vertical = [ ] NEW_LINE horizontal = [ ] NEW_LINE for i in range ( ROW ) : NEW_LINE INDENT for j in range ( COL ) : NEW_LINE INDENT if grid [ i ] [ j ] == 1 : NEW_LINE INDENT vertical . append ( i ) NEW_LINE horizontal . append ( j ) NEW_LINE DEDENT DEDENT DEDENT vertical . sort ( ) NEW_LINE horizontal . sort ( ) NEW_LINE size = len ( vertical ) // 2 NEW_LINE x = vertical [ size ] NEW_LINE y = horizontal [ size ] NEW_LINE distance = 0 NEW_LINE for i in range ( ROW ) : NEW_LINE INDENT for j in range ( COL ) : NEW_LINE INDENT if grid [ i ] [ j ] == 1 : NEW_LINE INDENT distance += abs ( x - i ) + abs ( y - j ) NEW_LINE DEDENT DEDENT DEDENT return distance NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT grid = [ [ 1 , 0 , 1 , 0 , 1 ] , [ 0 , 1 , 0 , 0 , 0 ] , [ 0 , 1 , 1 , 0 , 0 ] ] NEW_LINE print ( minTotalDistance ( grid ) ) NEW_LINE DEDENT