Distance of nearest cell having 1 in a binary matrix | Prthe distance of nearest cell having 1 for each cell . ; Initialize the answer matrix with INT_MAX . ; For each cell ; Traversing the whole matrix to find the minimum distance . ; If cell contain 1 , check for minimum distance . ; Printing the answer . ; Driver Code
def printDistance ( mat ) : NEW_LINE INDENT global N , M NEW_LINE ans = [ [ None ] * M for i in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT ans [ i ] [ j ] = 999999999999 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT for k in range ( N ) : NEW_LINE INDENT for l in range ( M ) : NEW_LINE INDENT if ( mat [ k ] [ l ] == 1 ) : NEW_LINE INDENT ans [ i ] [ j ] = min ( ans [ i ] [ j ] , abs ( i - k ) + abs ( j - l ) ) NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT print ( ans [ i ] [ j ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT N = 3 NEW_LINE M = 4 NEW_LINE mat = [ [ 0 , 0 , 0 , 1 ] , [ 0 , 0 , 1 , 1 ] , [ 0 , 1 , 1 , 0 ] ] NEW_LINE printDistance ( mat ) NEW_LINE