Skip to content

Commit 2aa2e79

Browse files
Commit explanation of optimized approach
1 parent 5bbd9da commit 2aa2e79

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
Intuition
2+
step 1: make graph
3+
step 2: Floyd-Warshall algorithm to find the minimum transformation costs between all pairs of characters
4+
5+
Approach
6+
The goal is to transform the string source into the string target using the minimal cost specified in the cost array. The transformation rules are defined by the original and changed arrays, where original[i] can be changed to changed[i] at a cost of cost[i].
7+
8+
Complexity
9+
Time complexity:
10+
O(m+n^3)
11+
12+
Space complexity:
13+
O(n^2)
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
class Solution
2+
{
3+
public:
4+
long long minimumCost(string source, string target, vector<char> &original, vector<char> &changed, vector<int> &cost)
5+
{
6+
int n = 26;
7+
vector<vector<int>> grid(n, vector<int>(n, INT_MAX));
8+
for (int i = 0; i < n; i++)
9+
{
10+
grid[i][i] = 0;
11+
}
12+
13+
for (int i = 0; i < original.size(); i++)
14+
{
15+
int from = original[i] - 'a';
16+
int to = changed[i] - 'a';
17+
grid[from][to] = min(grid[from][to], cost[i]);
18+
}
19+
20+
for (int via = 0; via < n; via++)
21+
{
22+
for (int i = 0; i < n; i++)
23+
{
24+
for (int j = 0; j < n; j++)
25+
{
26+
if (grid[i][via] != INT_MAX && grid[via][j] != INT_MAX)
27+
{
28+
grid[i][j] = min(grid[i][j], grid[i][via] + grid[via][j]);
29+
}
30+
}
31+
}
32+
}
33+
34+
long long ans = 0;
35+
for (int i = 0; i < source.size(); i++)
36+
{
37+
if (source[i] != target[i])
38+
{
39+
int cost = grid[source[i] - 'a'][target[i] - 'a'];
40+
if (cost == INT_MAX)
41+
return -1;
42+
ans += cost;
43+
}
44+
}
45+
return ans;
46+
}
47+
};

0 commit comments

Comments
 (0)