|
| 1 | +package com.fishercoder.solutions.thirdthousand; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.HashMap; |
| 6 | +import java.util.LinkedList; |
| 7 | +import java.util.List; |
| 8 | +import java.util.Map; |
| 9 | +import java.util.Queue; |
| 10 | + |
| 11 | +public class _2976 { |
| 12 | + public static class Solution1 { |
| 13 | + /** |
| 14 | + * My completely original solution to use Dijkstra's algorithm. |
| 15 | + * Dijkstra's algorithm is the way to go for finding |
| 16 | + * the shortest path in a weighted (non-negative) graph. |
| 17 | + */ |
| 18 | + public long minimumCost(String source, String target, char[] original, char[] changed, int[] cost) { |
| 19 | + int ALPHABET_SIZE = 26; |
| 20 | + List<int[]>[] graph = new ArrayList[ALPHABET_SIZE]; |
| 21 | + for (int i = 0; i < ALPHABET_SIZE; i++) { |
| 22 | + graph[i] = new ArrayList<>(); |
| 23 | + } |
| 24 | + for (int i = 0; i < original.length; i++) { |
| 25 | + graph[original[i] - 'a'].add(new int[]{changed[i] - 'a', cost[i]}); |
| 26 | + } |
| 27 | + long minCost = 0L; |
| 28 | + Map<String, Long> cache = new HashMap<>(); |
| 29 | + for (int i = 0; i < source.length(); i++) { |
| 30 | + long thisCost = dijkstra(source.charAt(i) - 'a', target.charAt(i) - 'a', graph, cache); |
| 31 | + if (thisCost != -1) { |
| 32 | + minCost += thisCost; |
| 33 | + } else { |
| 34 | + return -1; |
| 35 | + } |
| 36 | + } |
| 37 | + return minCost; |
| 38 | + } |
| 39 | + |
| 40 | + private long dijkstra(int source, int target, List<int[]>[] graph, Map<String, Long> cache) { |
| 41 | + if (cache.containsKey(source + "->" + target)) { |
| 42 | + return cache.get(source + "->" + target); |
| 43 | + } |
| 44 | + int[] minCosts = new int[26]; |
| 45 | + Arrays.fill(minCosts, Integer.MAX_VALUE); |
| 46 | + minCosts[source] = 0; |
| 47 | + Queue<int[]> q = new LinkedList<>(); |
| 48 | + q.offer(new int[]{source, 0}); |
| 49 | + while (!q.isEmpty()) { |
| 50 | + int[] curr = q.poll(); |
| 51 | + int currNode = curr[0]; |
| 52 | + int currCost = curr[1]; |
| 53 | + if (currCost > minCosts[currNode]) { |
| 54 | + continue; |
| 55 | + } |
| 56 | + for (int[] neighbor : graph[currNode]) { |
| 57 | + int neighborNode = neighbor[0]; |
| 58 | + int neighborCost = neighbor[1]; |
| 59 | + if (currCost + neighborCost < minCosts[neighborNode]) { |
| 60 | + minCosts[neighborNode] = currCost + neighborCost; |
| 61 | + q.offer(new int[]{neighborNode, minCosts[neighborNode]}); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + if (minCosts[target] == Integer.MAX_VALUE) { |
| 66 | + minCosts[target] = -1; |
| 67 | + } |
| 68 | + cache.put(source + "->" + target, (long) minCosts[target]); |
| 69 | + return cache.getOrDefault(source + "->" + target, -1L); |
| 70 | + } |
| 71 | + |
| 72 | + } |
| 73 | +} |
0 commit comments