Minimize cost of placing tiles of dimensions 2 * 1 over a Matrix | Function to find the minimum cost in placing N tiles in a grid M [ ] [ ] ; Stores the minimum profit after placing i tiles ; Traverse the grid [ ] [ ] ; Update the orig_cost ; Traverse over the range [ 2 , N ] ; Place tiles horizentally or vertically ; Print the answer ; Driver Code
def tile_placing ( grid , N ) : NEW_LINE INDENT dp = [ 0 ] * ( N + 5 ) ; NEW_LINE orig_cost = 0 ; NEW_LINE for i in range ( 2 ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT orig_cost += grid [ i ] [ j ] ; NEW_LINE DEDENT DEDENT dp [ 0 ] = 0 ; NEW_LINE dp [ 1 ] = abs ( grid [ 0 ] [ 0 ] - grid [ 1 ] [ 0 ] ) ; NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i - 1 ] + abs ( grid [ 0 ] [ i - 1 ] - grid [ 1 ] [ i - 1 ] ) , dp [ i - 2 ] + abs ( grid [ 0 ] [ i - 2 ] - grid [ 0 ] [ i - 1 ] ) + abs ( grid [ 1 ] [ i - 2 ] - grid [ 1 ] [ i - 1 ] ) ) ; NEW_LINE DEDENT print ( orig_cost - dp [ N ] , end = " " ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT M = [ [ 7 , 5 , 1 , 3 ] , [ 8 , 6 , 0 , 2 ] ] ; NEW_LINE N = len ( M [ 0 ] ) ; NEW_LINE tile_placing ( M , N ) ; NEW_LINE DEDENT