Program to find minimum cost to paint fences with k different colors in Python

Suppose we want to paint a row of N fences with K different colors. We want to minimize the cost while ensuring that no two neighboring fences are of the same color. So if we have an N x K matrix where the nth row and kth column represents the cost to paint the nth fence with kth color, we have to find the minimum cost which achieves this goal.

So, if the input is like ?

6 4 5
3 2 7
3 4 5
5 4 4

then the output will be 14, as we can select the following color indices (starting from the first fence) ? Color 2 ? Color 1 ? Color 0 ? Color 2 with costs 4 + 3 + 3 + 4 = 14.

Algorithm

To solve this, we will follow these steps ?

  • n := row count of matrix

  • fc := 0, ft := 0 (first color index and first minimum cost)

  • sc := 1, st := 0 (second color index and second minimum cost)

  • for each row in matrix, do

    • nfc := -1, nft := infinity (new first color and cost)

    • nsc := -1, nst := infinity (new second color and cost)

    • for each index i and value t in row, do

      • ct := t + (ft if i is not same as fc otherwise st)

      • if ct ? nft, then

        • nsc := nfc, nst := nft

        • nfc := i, nft := ct

      • otherwise when ct ? nst, then

        • nsc := i, nst := ct

    • fc := nfc, ft := nft

    • sc := nsc, st := nst

  • return ft

Example

Let us see the following implementation to get better understanding ?

class Solution:
    def solve(self, matrix):
        n = len(matrix)
        fc, ft = 0, 0
        sc, st = 1, 0
        inf = int(1e18)
        for row in matrix:
            nfc, nft = -1, inf
            nsc, nst = -1, inf
            for i, t in enumerate(row):
                ct = t + (ft if i != fc else st)
                if ct <= nft:
                    nsc, nst = nfc, nft
                    nfc, nft = i, ct
                elif ct <= nst:
                    nsc, nst = i, ct
            fc, ft = nfc, nft
            sc, st = nsc, nst
        return ft

ob = Solution()
matrix = [
    [6, 4, 5],
    [3, 2, 7],
    [3, 4, 5],
    [5, 4, 4]
]
print(ob.solve(matrix))
14

How It Works

The algorithm maintains the two minimum costs for each row to avoid adjacent fences having the same color. For each fence, it calculates the minimum cost by either choosing the previous minimum (if different color) or the second minimum (if same color). This dynamic programming approach ensures we find the optimal solution efficiently.

Alternative Approach Using Dynamic Programming

Here's a more intuitive solution using traditional DP ?

def min_cost_fence_painting(matrix):
    if not matrix or not matrix[0]:
        return 0
    
    n, k = len(matrix), len(matrix[0])
    
    # dp[i][j] represents minimum cost to paint fence i with color j
    dp = [[0] * k for _ in range(n)]
    
    # Base case: first fence
    for j in range(k):
        dp[0][j] = matrix[0][j]
    
    # Fill the dp table
    for i in range(1, n):
        for j in range(k):
            dp[i][j] = matrix[i][j] + min(dp[i-1][l] for l in range(k) if l != j)
    
    # Return minimum cost for the last fence
    return min(dp[n-1])

# Test with the same example
matrix = [
    [6, 4, 5],
    [3, 2, 7],
    [3, 4, 5],
    [5, 4, 4]
]
print(min_cost_fence_painting(matrix))
14

Conclusion

Both approaches solve the fence painting problem efficiently. The first method optimizes space by tracking only the two minimum values, while the second uses a traditional DP table for better readability. The key insight is avoiding adjacent fences with the same color while minimizing total cost.

Updated on: 2026-03-25T13:47:49+05:30

356 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements