|
| 1 | +class Solution: |
| 2 | + def minimumCost(self, |
| 3 | + source: str, |
| 4 | + target: str, |
| 5 | + original: List[str], |
| 6 | + changed: List[str], |
| 7 | + cost: List[int]) -> int: |
| 8 | + |
| 9 | + # Create mapping of each letter to their cheapest counterparts |
| 10 | + conversions = [{} for _ in range(26)] |
| 11 | + for o, n, c in zip(original, changed, cost) : |
| 12 | + if o == n : |
| 13 | + continue |
| 14 | + if (ord(n) - ord('a')) not in conversions[ord(o) - ord('a')] \ |
| 15 | + or conversions[ord(o) - ord('a')][ord(n) - ord('a')] > c : |
| 16 | + conversions[ord(o) - ord('a')][ord(n) - ord('a')] = c |
| 17 | + |
| 18 | + # Propogate from each point to find all reachable characters |
| 19 | + # and calculate the min cost using Diskstras and a heap. |
| 20 | + for i in range(26) : |
| 21 | + # schema: (cost, target) |
| 22 | + hp = [(c, x) for x, c in conversions[i].items()] |
| 23 | + heapq.heapify(hp) |
| 24 | + |
| 25 | + while hp : |
| 26 | + c, x = heapq.heappop(hp) |
| 27 | + if x not in conversions[i] or c <= conversions[i][x] : |
| 28 | + conversions[i][x] = c |
| 29 | + |
| 30 | + # from x to target at newCost |
| 31 | + for tar, newCost in conversions[x].items() : |
| 32 | + if tar not in conversions[i] \ |
| 33 | + or newCost + c <= conversions[i][tar] : |
| 34 | + heapq.heappush(hp, (newCost + c, tar)) |
| 35 | + |
| 36 | + # Iterate through the starting string and use the previously |
| 37 | + # computed path-cost mapping to calculate cost |
| 38 | + tot_cost = 0 |
| 39 | + for o, c in zip(source, target) : |
| 40 | + if o == c : |
| 41 | + continue |
| 42 | + elif (ord(c) - ord('a')) not in conversions[ord(o) - ord('a')] : |
| 43 | + return -1 |
| 44 | + else : |
| 45 | + tot_cost += conversions[ord(o) - ord('a')].get(ord(c) - ord('a')) |
| 46 | + |
| 47 | + return tot_cost |
0 commit comments