


The first line contains an integer ‘T’ denoting the number of test cases. Then each test case follows.
The first input line of each test case contains an integer ‘N’ denoting the number of houses.
Each of the next ‘N’ lines contains 3 space-separated integers denoting the cost of painting the i-th house with the green,red and yellow color respectively.
For each test case, print the minimum cost of painting all houses such that no adjacent houses are painted with the same colour.
Print the output of each test case in a separate line.
You are not required to print the expected output; it has already been taken care of. Just implement the function.
1 <= T <= 50
1 <= N <= 10000
0 <= cost[i][j] <= 100
Where cost[i][j] represents the cost of painting the i-th house with j-th colour.
Time limit: 1 sec
The basic idea of this approach is to break the original problem into sub-problems. We will try to check each valid way of painting the houses. And, then find the minimum cost.
Now, let us define a recursive function
getMinCost(int i, int j)Which returns the minimum cost to paint the first ‘i’ houses (0-th based indexing) such that the last house (i-th house) is painted with j-th colour.
Algorithm
Let us observe the recursion tree for the first test case of sample test 2.
After observing the tree, we’ll find that there are some redundant function calls which means that there are some overlapping subproblems. The repetition of such sub-problems suggests that we can use dynamic programming to optimize our approach.
The key idea behind a dynamic programming approach is to use memoization, i.e. we’ll save the result of our sub-problem in a matrix so that it can be used later on.
Let dp[ i ][ j ] be our dynamic programming matrix of N * 3 dimensions to store the minimum cost to paint first ‘i’ houses such that the i-th house is painted with j-th colour.
Now, consider the following steps to implement the getMinCost(int i, int j) function along with memoization :
The basic idea of this approach is to solve the problem iteratively.
Let dp[ i ][ j ] be our dynamic programming matrix of N * 3 dimensions to store the minimum cost to paint first ‘i’ houses such that the i-th house is painted with j-th colour.
Algorithm
We can observe in approach 3 that the current state depends on one immediate previous house. This suggests we can use three variables to store the cost of painting the previous house with given colors.
Let “lastGreen”, “lastRed” and “lastYellow” be three variables that store the cost if the last house is painted with green, red and yellow color, respectively.
Algorithm