# Program to find minimum cost for painting houses in Python

PythonServer Side ProgrammingProgramming

Suppose there is an array of size m, represents m houses in a small city, each house must be painted with one of the n colors (the colors are labeled from 1 to n), And some houses are already painted, so no need to paint again. Those houses which are colored with same color are called neighborhood. We have the array houses, where houses[i] represents the color of the house, if the color value is 0, then it represents the house is not colored yet. We have another array called costs, this is a 2D array where costs[i, j] represents the cost to color house i with color j+1. We also have another input value called target. We have to find the minimum cost needed to painting all the remaining houses in such a way that there are exactly target number of neighborhoods. If we cannot get a solution then return -1.

So, if the input is like houses = [0,2,1,2,0] cost = [[1,10],[10,1],[10,1],[1,10],[5,1]] n = 2 target = 3, then the output will be 11 because some houses are already painted, so we have to paint the houses in such a way like [2,2,1,2,2], There are three neighborhoods, [{2,2}, {1}, {2,2}]. And total cost to paint the first and last house (10 + 1) = 11.

To solve this, we will follow these steps −

• m := size of houses

• Define a function helper() . This will take i, p_col, grp

• if i is same as m, then

• return 0 if grp is same as target otherwise inf

• if houses[i] is not same as 0, then

• return helper(i + 1, houses[i], grp + (1 if p_col is not same as houses[i], otherwise 0)

• total := inf

• for col in range 1 to n, do

• total = minimum of total and (cost[i, col - 1] + helper(i + 1, col, grp + (1 when p_col is not same as col otherwise 0)))

• From the main method do the following

• ans := helper(0, -1, 0)

• return ans if ans is not inf otherwise -1

## Example

Let us see the following implementation to get better understanding

def solve(houses, cost, n, target):
m = len(houses)

def helper(i, p_col, grp):
if i == m:

return 0 if grp == target else float('inf')

if houses[i] != 0:
return helper(i + 1, houses[i], grp + int(p_col != houses[i]))

total = float('inf')
for col in range(1, n + 1):
total = min(total, cost[i][col - 1] + helper(i + 1, col, grp + int(p_col != col)))

ans = helper(0, -1, 0)
return ans if ans != float('inf') else -1

houses = [0,2,1,2,0]

cost = [[1,10],[10,1],[10,1],[1,10],[5,1]]

n = 2

target = 3

print(solve(houses, cost, n, target))

## Input

[0,2,1,2,0], [[1,10],[10,1],[10,1],[1,10],[5,1]], 2, 3


## Output

11
Published on 06-Oct-2021 07:46:26