Skip to content

Commit 278e098

Browse files
authored
Create the-most-similar-path-in-a-graph.cpp
1 parent 76f15c1 commit 278e098

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Time: O(n^2 * m), m is the length of targetPath
2+
// Space: O(n * m)
3+
4+
class Solution {
5+
public:
6+
vector<int> mostSimilar(int n, vector<vector<int>>& roads, vector<string>& names, vector<string>& targetPath) {
7+
vector<vector<int>> adj(n);
8+
for (const auto& road : roads) {
9+
adj[road[0]].emplace_back(road[1]);
10+
adj[road[1]].emplace_back(road[0]);
11+
}
12+
13+
vector<vector<int>> dp(targetPath.size() + 1, vector<int>(n));
14+
for (int i = 1; i <= targetPath.size(); ++i) {
15+
for (int v = 0; v < n; ++v) {
16+
dp[i][v] = targetPath.size();
17+
for (const auto& u : adj[v]) {
18+
dp[i][v] = min(dp[i][v], dp[i - 1][u]);
19+
}
20+
dp[i][v] += int(names[v] != targetPath[i - 1]);
21+
}
22+
}
23+
24+
vector<int> path = {static_cast<int>(distance(cbegin(dp.back()),
25+
min_element(cbegin(dp.back()), cend(dp.back()))))};
26+
for (int i = targetPath.size(); i >= 2; --i) {
27+
for (const auto& u : adj[path.back()]) {
28+
if (dp[i - 1][u] + int(names[path.back()] != targetPath[i - 1]) == dp[i][path.back()]) {
29+
path.emplace_back(u);
30+
break;
31+
}
32+
}
33+
}
34+
reverse(begin(path), end(path));
35+
return path;
36+
}
37+
};

0 commit comments

Comments
 (0)