text: Minimum Distance from a given Cell to all other Cells of a Matrix | Python3 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: mat = [ [ 0 for x in range ( 1001 ) ] for y in range ( 1001 ) ] NEW_LINE dx = [ 0 , - 1 , - 1 , - 1 , 0 , 1 , 1 , 1 ] NEW_LINE dy = [ 1 , 1 , 0 , - 1 , - 1 , - 1 , 0 , 1 ] NEW_LINE def FindMinimumDistance ( ) : NEW_LINE INDENT global x , y , r , c NEW_LINE q = [ ] NEW_LINE q . append ( [ x , y ] ) NEW_LINE mat [ x ] [ y ] = 0 NEW_LINE while ( len ( q ) != 0 ) : NEW_LINE INDENT x = q [ 0 ] [ 0 ] NEW_LINE y = q [ 0 ] [ 1 ] NEW_LINE q . pop ( 0 ) NEW_LINE for i in range ( 8 ) : NEW_LINE INDENT a = x + dx [ i ] NEW_LINE b = y + dy [ i ] NEW_LINE if ( a < 0 or a >= r or b >= c or b < 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( mat [ a ] [ b ] == 0 ) : NEW_LINE INDENT mat [ a ] [ b ] = mat [ x ] [ y ] + 1 NEW_LINE q . append ( [ a , b ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT r = 5 NEW_LINE c = 5 NEW_LINE x = 1 NEW_LINE y = 1 NEW_LINE t = x NEW_LINE l = y NEW_LINE mat [ x ] [ y ] = 0 NEW_LINE FindMinimumDistance ( ) NEW_LINE mat [ t ] [ l ] = 0 NEW_LINE for i in range ( r ) : NEW_LINE INDENT for j in range ( c ) : NEW_LINE INDENT print ( mat [ i ] [ j ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT