Untitled
unknown
plain_text
9 months ago
1.9 kB
7
Indexable
public class PaintHouses {
public int minCost(int[][] costs) {
if (costs == null || costs.length == 0) {
return 0;
}
return helper(costs, 0, -1);
}
private int helper(int[][] costs, int houseIndex, int prevColor) {
// Base case: If all houses are painted, return 0
if (houseIndex == costs.length) {
return 0;
}
int minCost = Integer.MAX_VALUE;
// Try all colors for the current house
for (int color = 0; color < costs[0].length; color++) {
// Ensure that the current color is not the same as the previous color
if (color != prevColor) {
// Calculate the cost for the current house and recursively for the next houses
int currentCost = costs[houseIndex][color] + helper(costs, houseIndex + 1, color);
// Update the minimum cost
minCost = Math.min(minCost, currentCost);
}
}
return minCost;
}
public static void main(String[] args) {
PaintHouses solution = new PaintHouses();
// Sample Input 1
int[][] costs1 = {
{1, 5, 3},
{2, 9, 4}
};
System.out.println(solution.minCost(costs1)); // Output: 5
// Sample Input 2
int[][] costs2 = {
{1, 4, 5},
{2, 3, 5},
{6, 7, 8}
};
System.out.println(solution.minCost(costs2)); // Output: 10
// Additional Test Case
int[][] costs3 = {
{1, 2, 3},
{10, 11, 12}
};
System.out.println(solution.minCost(costs3)); // Output: 12
int[][] costs4 = {
{4, 2}
};
System.out.println(solution.minCost(costs4)); // Output: 2
}
}Editor is loading...
Leave a Comment