Minimize total cost without repeating same task in two consecutive iterations | Function to return the minimum cost for N iterations ; Construct the dp table ; 1 st row of dp table will be equal to the 1 st of cost matrix ; Iterate through all the rows ; To iterate through the columns of current row ; Initialize val as infinity ; To iterate through the columns of previous row ; Fill the dp matrix ; Returning the minimum value ; Driver Code ; Number of iterations ; Number of tasks ; Cost matrix
def findCost ( cost_mat , N , M ) : NEW_LINE INDENT dp = [ [ 0 ] * M for _ in range ( M ) ] NEW_LINE dp [ 0 ] = cost_mat [ 0 ] NEW_LINE for row in range ( 1 , N ) : NEW_LINE INDENT for curr_col in range ( M ) : NEW_LINE INDENT val = 999999999 NEW_LINE for prev_col in range ( M ) : NEW_LINE INDENT if curr_col != prev_col : NEW_LINE INDENT val = min ( val , dp [ row - 1 ] [ prev_col ] ) NEW_LINE DEDENT DEDENT dp [ row ] [ curr_col ] = val + cost_mat [ row ] [ curr_col ] NEW_LINE DEDENT DEDENT return min ( dp [ - 1 ] ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 NEW_LINE M = 4 NEW_LINE cost_mat = [ [ 4 , 5 , 3 , 2 ] , [ 6 , 2 , 8 , 1 ] , [ 6 , 2 , 2 , 1 ] , [ 0 , 5 , 5 , 1 ] ] NEW_LINE print ( findCost ( cost_mat , N , M ) ) NEW_LINE DEDENT