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: #include <bits/stdc++.h> NEW_LINE using namespace std ; int mat [ 1001 ] [ 1001 ] ; int r , c , x , y ; int dx [ ] = { 0 , -1 , -1 , -1 , 0 , 1 , 1 , 1 } ; int dy [ ] = { 1 , 1 , 0 , -1 , -1 , -1 , 0 , 1 } ; void FindMinimumDistance ( ) { queue < pair < int , int > > q ; q . push ( { x , y } ) ; mat [ x ] [ y ] = 0 ; while ( ! q . empty ( ) ) { x = q . front ( ) . first ; y = q . front ( ) . second ; q . pop ( ) ; 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 . push ( { a , b } ) ; } } } } int main ( ) { 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 ++ ) { cout << mat [ i ] [ j ] << " ▁ " ; } cout << endl ; } }