Minimum Distance from a given Cell to all other Cells of a Matrix | Javascript Program to implement the above approach ; Stores the accessible directions ; Function to find the minimum distance from a given cell to all other cells in the matrix ; Stores the accessible cells from current cell ; Insert pair ( x , y ) ; Iterate untill queue is empty ; Extract the pair ; Pop them ; Checking boundary condition ; If the cell is not visited ; Assign the minimum distance ; Insert the traversed neighbour into the queue ; Driver Code ; Print the required distances
let mat = new Array ( 1001 ) ; for ( let i = 0 ; i < 1001 ; i ++ ) { mat [ i ] = new Array ( 1001 ) ; for ( let j = 0 ; j < 1001 ; j ++ ) { mat [ i ] [ j ] = 0 ; } } let r , c , x , y ; let dx = [ 0 , - 1 , - 1 , - 1 , 0 , 1 , 1 , 1 ] ; let dy = [ 1 , 1 , 0 , - 1 , - 1 , - 1 , 0 , 1 ] ; function FindMinimumDistance ( ) { let q = [ ] ; q . push ( [ x , y ] ) ; mat [ x ] [ y ] = 0 ; while ( q . length > 0 ) { x = q [ 0 ] [ 0 ] ; y = q [ 0 ] [ 1 ] ; q . shift ( ) ; for ( let i = 0 ; i < 8 ; i ++ ) { let a = x + dx [ i ] ; let b = y + dy [ i ] ; if ( a < 0 a >= r b >= c b < 0 ) continue ; if ( mat [ a ] [ b ] == 0 ) { mat [ a ] [ b ] = mat [ x ] [ y ] + 1 ; q . push ( [ a , b ] ) ; } } } } r = 5 , c = 5 , x = 1 , y = 1 ; let t = x ; let l = y ; mat [ x ] [ y ] = 0 ; FindMinimumDistance ( ) ; mat [ t ] [ l ] = 0 ; for ( let i = 0 ; i < r ; i ++ ) { for ( let j = 0 ; j < c ; j ++ ) { document . write ( mat [ i ] [ j ] + " " ) ; } document . write ( " " ) ; }