Minimize steps required to move all 1 's in a matrix to a given index | Function to calculate and return the minimum number of steps required to move all 1 s to ( X , Y ) ; Iterate the given matrix ; Update the answer with minimum moves required for the given element to reach the given index ; Return the number of steps ; Given matrix ; Given position ; Function call
def findAns ( mat , x , y , n , m ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 1 ) : NEW_LINE INDENT ans += ( abs ( x - i ) + abs ( y - j ) ) NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT mat = [ [ 1 , 0 , 0 , 0 ] , [ 0 , 1 , 0 , 1 ] , [ 1 , 0 , 1 , 1 ] ] NEW_LINE x = 0 NEW_LINE y = 2 NEW_LINE print ( findAns ( mat , x , y , len ( mat ) , len ( mat [ 0 ] ) ) ) NEW_LINE