Find minimum moves to bring all elements in one cell of a matrix | Python3 implementation to find the minimum number of moves to bring all non - zero element in one cell of the matrix ; Function to find the minimum number of moves to bring all elements in one cell of matrix ; Moves variable to store the sum of number of moves ; Loop to count the number of the moves ; Condition to check that the current cell is a non - zero element ; Driver Code ; Coordinates of given cell ; Given Matrix ; Element to be moved ; Function call
M = 4 NEW_LINE N = 5 NEW_LINE def no_of_moves ( Matrix , x , y ) : NEW_LINE INDENT moves = 0 NEW_LINE for i in range ( M ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if ( Matrix [ i ] [ j ] != 0 ) : NEW_LINE INDENT moves += abs ( x - i ) NEW_LINE moves += abs ( y - j ) NEW_LINE DEDENT DEDENT DEDENT print ( moves ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 3 NEW_LINE y = 2 NEW_LINE Matrix = [ [ 1 , 0 , 1 , 1 , 0 ] , [ 0 , 1 , 1 , 0 , 1 ] , [ 0 , 0 , 1 , 1 , 0 ] , [ 1 , 1 , 1 , 0 , 0 ] ] NEW_LINE num = 1 NEW_LINE no_of_moves ( Matrix , x , y ) NEW_LINE DEDENT