There is a row of n houses, and each house can be painted with one of k colors. The cost of painting a house depends on both the house and the color. You have to paint all the houses so that no two adjacent houses have the same color.
The costs are given as an n x k matrix costs, where costs[i][j] is the cost of painting house i with color j.
Return the minimum total cost to paint all the houses.
Function Signature
def min_cost(costs: list[list[int]]) -> int:
Rules
-
Colors are numbered
0
to
k - 1
, one per column of
costs
.
-
Only houses
i
and
i + 1
count as adjacent. Houses that are further apart may share a color.
-
Return only the minimum total cost, not the colors chosen.
Constraints
-
n == len(costs)
-
k == len(costs[i])
for every
i
-
1 <= n <= 100
-
2 <= k <= 20
-
1 <= costs[i][j] <= 20
Examples
Input: costs = [[1, 5, 3], [2, 9, 4]]
Output: 5
Paint house 0 with color 0 (cost 1) and house 1 with color 2 (cost 4), for a total of 1 + 4 = 5. Color 2 then color 0 (3 + 2) also costs 5, and both houses cannot take their cheapest color 0.
Input: costs = [[1, 3], [2, 4]]
Output: 5
With two colors the houses must alternate. Color 0 then color 1 costs 1 + 4 = 5, and color 1 then color 0 costs 3 + 2 = 5.
Input: costs = [[2, 5, 7, 4], [1, 6, 3, 8], [2, 4, 9, 6]]
Output: 7
Color 0 is the cheapest for every house. Houses 0 and 2 are not adjacent, so both can take color 0 (2 + 2), and house 1 takes color 2 at 3, for 7. Giving house 1 color 0 instead would push houses 0 and 2 onto colors costing 4 each, for 4 + 1 + 4 = 9.