You have been given ‘N’ houses, each house can be painted with any of three colours: green, red and yellow. You are also given a “cost” matrix of ‘N’ * 3 dimension which represents the cost of painting an i-th house (0-th based indexing) with j-th colour. The colour code is as follows: green - 0, red - 1 and yellow - 2. Now, you are supposed to find the minimum cost of painting all houses such that no adjacent houses are painted with the same colour.
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.
Output Format :
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.
Note :
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
2
2
2 3 2
1 4 1
1
1 2 3
3
1
For the first test case, in the optimal case, we can paint house 0 (0-th based indexing) with colour 0 (0-th based indexing) and house 1 with colour 2. The cost will be 2 + 1 = 3.
For the second test case, we can choose the colour 0 to paint the house. And the cost will be 1.
2
3
14 2 11
11 14 5
14 3 10
2
1 2 3
1 4 6
10
3
For the first test case, in the optimal case, we can paint house 0 (0-th based indexing) with colour 1 (0-th based indexing), house 1 with colour 2 and house 2 with colour 1. The cost will be 2 + 5 + 3 = 10.
For the second test case, the minimum cost will be 3.
Can you think of breaking the problem into sub-problems?
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
O(2 ^ (N)), where ‘N’ is the total number of houses.
Since we are checking every valid way of painting the houses and there are will be 3 * 2 ^(N) such ways. So, the overall time complexity will be O(2 ^ (N)).
O(N), where ‘N’ is the total number of houses.
Since we are using a recursive function to find the minimum cost and in the worst case, there may be N state in the call stack. So the overall space complexity will be O(N).