Minimize cost of placing tiles of dimensions 2 * 1 over a Matrix | C # program for the above approach ; 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
using System ; class GFG { static void tile_placing ( int [ , ] grid , int N ) { int [ ] dp = new int [ N + 5 ] ; for ( int i = 0 ; i < N + 5 ; i ++ ) { dp [ i ] = 0 ; } int orig_cost = 0 ; for ( int i = 0 ; i < 2 ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { orig_cost += grid [ i , j ] ; } } dp [ 0 ] = 0 ; dp [ 1 ] = Math . Abs ( grid [ 0 , 0 ] - grid [ 1 , 0 ] ) ; for ( int i = 2 ; i <= N ; i ++ ) { dp [ i ] = Math . Max ( dp [ i - 1 ] + Math . Abs ( grid [ 0 , i - 1 ] - grid [ 1 , i - 1 ] ) , dp [ i - 2 ] + Math . Abs ( grid [ 0 , i - 2 ] - grid [ 0 , i - 1 ] ) + Math . Abs ( grid [ 1 , i - 2 ] - grid [ 1 , i - 1 ] ) ) ; } Console . Write ( orig_cost - dp [ N ] ) ; } public static void Main ( ) { int [ , ] M = { { 7 , 5 , 1 , 3 } , { 8 , 6 , 0 , 2 } } ; int N = 4 ; tile_placing ( M , N ) ; } }