Maximum of all distances to the nearest 1 cell from any 0 cell in a Binary matrix | Python3 program to find the maximum distance from a 0 - cell to a 1 - cell ; If the matrix consists of only 0 ' s ▁ ▁ or ▁ only ▁ 1' s ; If it 's a 0-cell ; Calculate its distance with every 1 - cell ; Compare and store the minimum ; Compare ans store the maximum ; Driver code
def maxDistance ( grid ) : NEW_LINE INDENT one = [ ] NEW_LINE M = len ( grid ) NEW_LINE N = len ( grid [ 0 ] ) NEW_LINE ans = - 1 NEW_LINE for i in range ( M ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE if ( grid [ i ] [ j ] == 1 ) : NEW_LINE INDENT one . append ( [ i , j ] ) NEW_LINE DEDENT DEDENT if ( one == [ ] or M * N == len ( one ) ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE if ( grid [ i ] [ j ] == 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT dist = float ( ' inf ' ) NEW_LINE for p in one : NEW_LINE INDENT d = abs ( p [ 0 ] - i ) + abs ( p [ 1 ] - j ) NEW_LINE dist = min ( dist , d ) NEW_LINE if ( dist <= ans ) : NEW_LINE break NEW_LINE ans = max ( ans , dist ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ [ 0 , 0 , 1 ] , [ 0 , 0 , 0 ] , [ 0 , 0 , 0 ] ] NEW_LINE print ( maxDistance ( arr ) ) NEW_LINE