Distance of nearest cell having 1 in a binary matrix | Javascript program to find distance of nearest cell having 1 in a binary matrix . ; Print the distance of nearest cell having 1 for each cell . ; Initialise the answer matrix with MaxValue . ; For each cell ; Traversing the whole matrix to find the minimum distance . ; If cell contain 1 , check for minimum distance . ; Printing the answer . ; Driven Program
let N = 3 ; let M = 4 ; function printDistance ( mat ) { let ans = new Array ( N ) ; for ( let i = 0 ; i < N ; i ++ ) { ans [ i ] = new Array ( M ) ; for ( let j = 0 ; j < M ; j ++ ) { ans [ i ] [ j ] = Number . MAX_VALUE ; } } for ( let i = 0 ; i < N ; i ++ ) for ( let j = 0 ; j < M ; j ++ ) { for ( let k = 0 ; k < N ; k ++ ) for ( let l = 0 ; l < M ; l ++ ) { if ( mat [ k ] [ l ] == 1 ) ans [ i ] [ j ] = Math . min ( ans [ i ] [ j ] , Math . abs ( i - k ) + Math . abs ( j - l ) ) ; } } for ( let i = 0 ; i < N ; i ++ ) { for ( let j = 0 ; j < M ; j ++ ) document . write ( ans [ i ] [ j ] + " " ) ; document . write ( " " ) ; } } let mat = [ [ 0 , 0 , 0 , 1 ] , [ 0 , 0 , 1 , 1 ] , [ 0 , 1 , 1 , 0 ] ] printDistance ( mat ) ;