text: Minimum Distance from a given Cell to all other Cells of a Matrix | C # 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
code: using System ; using System . Collections . Generic ; class GFG { class pair { public 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 Queue < pair > ( ) ; q . Enqueue ( new pair ( x , y ) ) ; mat [ x , y ] = 0 ; while ( q . Count != 0 ) { x = q . Peek ( ) . first ; y = q . Peek ( ) . second ; q . Dequeue ( ) ; 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 . Enqueue ( 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 ++ ) { Console . Write ( mat [ i , j ] + " ▁ " ) ; } Console . WriteLine ( ) ; } } }