GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — coding-problems/Dynamic Programming/min_cost_coloring.py at master · zsakhtar/coding-problems Expand file tree/ Copy pathmin_cost_coloring.pyMore file actions 68 lines (53 loc) · 2.03 KB / Copy pathmin_cost_coloring.pyFile metadata and controls68 lines (53 loc) · 2.03 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 ''' Min Cost Coloring A builder is looking to build a row of N houses that can be of K different colors. He has a goal of minimizing cost while ensuring that no two neighboring houses are of the same color. Given an N by K matrix where the nth row and kth column represents the cost to build the nth house with kth color, return the minimum cost which achieves this goal. ========================================= Dynamic programming, for each house search for the cheapest combination of the previous houses. But don't search the whole array with combinations (colors), save only the smallest 2 (in this case we're sure that the previous house doesn't have the same color). Time Complexity: O(N * K) Space Complexity: O(1) ''' ############ # Solution # ############ import math def min_cost_coloring(dp): # no need from a new dp matrix, you can use the input matrix n = len(dp) if n == 0: return 0 m = len(dp[0]) if m < 2: return -1 # save only the smallest 2 costs instead of searching the whole previous array prev_min = [(0, -1), (0, -1)] for i in range(n): curr_min = [(math.inf, -1), (math.inf, -1)] for j in range(m): # find result with different color if j != prev_min[0][1]: dp[i][j] += prev_min[0][0] else: dp[i][j] += prev_min[1][0] # save the current result if smaller than the current 2 if curr_min[0][0] > dp[i][j]: curr_min[1] = curr_min[0] curr_min[0] = (dp[i][j], j) elif curr_min[1][0] > dp[i][j]: curr_min[1] = (dp[i][j], j) prev_min = curr_min # return the min cost of the last house return min(dp[n - 1]) ########### # Testing # ########### # Test 1 # Correct result => 5 print(min_cost_coloring([[1, 2, 3, 4, 5], [5, 4, 3, 2, 1], [3, 2, 1, 4, 5], [3, 2, 1, 4, 3]])) # Test 2 # Correct result => 6 print(min_cost_coloring([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]])) |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |