-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathsolution.js
More file actions
31 lines (26 loc) · 868 Bytes
/
Copy pathsolution.js
File metadata and controls
31 lines (26 loc) · 868 Bytes
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
var minimumCost = function (source, target, original, changed, cost) {
const INF = 1e18;
const dist = Array.from({ length: 26 }, () => Array(26).fill(INF));
for (let i = 0; i < 26; i++) dist[i][i] = 0;
for (let i = 0; i < original.length; i++) {
const u = original[i].charCodeAt(0) - 97;
const v = changed[i].charCodeAt(0) - 97;
dist[u][v] = Math.min(dist[u][v], cost[i]);
}
// Floyd-Warshall
for (let k = 0; k < 26; k++) {
for (let i = 0; i < 26; i++) {
for (let j = 0; j < 26; j++) {
dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);
}
}
}
let ans = 0;
for (let i = 0; i < source.length; i++) {
const s = source.charCodeAt(i) - 97;
const t = target.charCodeAt(i) - 97;
if (dist[s][t] === INF) return -1;
ans += dist[s][t];
}
return ans;
};