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

645
327
345
544

then the output will be 14, as we can select the following color indices (starting from the first fence) − 5 → 2 → 3 → 4.

To solve this, we will follow these steps −

  • n := row count of matrix

  • fc := 0, ft := 0

  • sc := 1, st := 0

  • for each row in matrix, do

    • nfc := -1, nft := inf

    • nsc := -1, nst := inf

    • for each index i and value t 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 −

 Live Demo

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))

Input

[
   [6, 4, 5],
   [3, 2, 7],
   [3, 4, 5],
   [5, 4, 4]
]

Output

14

Updated on: 22-Dec-2020

224 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements