Sponsored
Sponsored
Use these hints if you're stuck. Try solving on your own first.
Construct a graph with each letter as a node, and construct an edge <code>(a, b)</code> with weight <code>c</code> if we can change from character <code>a</code> to letter <code>b</code> with cost <code>c</code>. (Keep the one with the smallest cost in case there are multiple edges between <code>a</code> and <code>b</code>).
Calculate the shortest path for each pair of characters <code>(source[i], target[i])</code>. The sum of cost over all <code>i</code> in the range <code>[0, source.length - 1]</code>. If there is no path between <code>source[i]</code> and <code>target[i]</code>, the answer is <code>-1</code>.
Any shortest path algorithms will work since we only have <code>26</code> nodes. Since we only have at most <code>26 * 26</code> pairs, we can save the result to avoid re-calculation.
We can also use Floyd Warshall's algorithm to precompute all the results.