Minimum Distance from a given Cell to all other Cells of a Matrix | Java 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
import java . util . * ; class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static int [ ] [ ] mat = new int [ 1001 ] [ 1001 ] ; static int r , c , x , y ; static int dx [ ] = { 0 , - 1 , - 1 , - 1 , 0 , 1 , 1 , 1 } ; static int dy [ ] = { 1 , 1 , 0 , - 1 , - 1 , - 1 , 0 , 1 } ; static void FindMinimumDistance ( ) { Queue < pair > q = new LinkedList < > ( ) ; q . add ( new pair ( x , y ) ) ; mat [ x ] [ y ] = 0 ; while ( ! q . isEmpty ( ) ) { x = q . peek ( ) . first ; y = q . peek ( ) . second ; q . remove ( ) ; for ( int i = 0 ; i < 8 ; i ++ ) { int a = x + dx [ i ] ; int 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 . add ( new pair ( a , b ) ) ; } } } } public static void main ( String [ ] args ) { r = 5 ; c = 5 ; x = 1 ; y = 1 ; int t = x ; int l = y ; mat [ x ] [ y ] = 0 ; FindMinimumDistance ( ) ; mat [ t ] [ l ] = 0 ; for ( int i = 0 ; i < r ; i ++ ) { for ( int j = 0 ; j < c ; j ++ ) { System . out . print ( mat [ i ] [ j ] + " ▁ " ) ; } System . out . println ( ) ; } } }