The Most Similar Path in a Graph Problem
Description
LeetCode Problem 1548.
We have n cities and m bi-directional roads where roads[i] = [a_i, b_i] connects city a_i with city b_i. Each city has a name consisting of exactly three upper-case English letters given in the string array names. Starting at any city x, you can reach any city y where y != x (i.e., the cities and the roads are forming an undirected connected graph).
You will be given a string array targetPath. You should find a path in the graph of the same length and with the minimum edit distance to targetPath.
You need to return the order of the nodes in the path with the minimum edit distance. The path should be of the same length of targetPath and should be valid (i.e., there should be a direct road between ans[i] and ans[i + 1]). If there are multiple answers return any one of them.
The edit distance is defined as follows:

Example 1:

Input: n = 5, roads = [[0,2],[0,3],[1,2],[1,3],[1,4],[2,4]], names = ["ATL","PEK","LAX","DXB","HND"], targetPath = ["ATL","DXB","HND","LAX"]
Output: [0,2,4,2]
Explanation: [0,2,4,2], [0,3,0,2] and [0,3,1,2] are accepted answers.
[0,2,4,2] is equivalent to ["ATL","LAX","HND","LAX"] which has edit distance = 1 with targetPath.
[0,3,0,2] is equivalent to ["ATL","DXB","ATL","LAX"] which has edit distance = 1 with targetPath.
[0,3,1,2] is equivalent to ["ATL","DXB","PEK","LAX"] which has edit distance = 1 with targetPath.
Example 2:

Input: n = 4, roads = [[1,0],[2,0],[3,0],[2,1],[3,1],[3,2]], names = ["ATL","PEK","LAX","DXB"], targetPath = ["ABC","DEF","GHI","JKL","MNO","PQR","STU","VWX"]
Output: [0,1,0,1,0,1,0,1]
Explanation: Any path in this graph has edit distance = 8 with targetPath.
Example 3:

Input: n = 6, roads = [[0,1],[1,2],[2,3],[3,4],[4,5]], names = ["ATL","PEK","LAX","ATL","DXB","HND"], targetPath = ["ATL","DXB","HND","DXB","ATL","LAX","PEK"]
Output: [3,4,5,4,3,2,1]
Explanation: [3,4,5,4,3,2,1] is the only path with edit distance = 0 with targetPath.
It's equivalent to ["ATL","DXB","HND","DXB","ATL","LAX","PEK"]
Constraints:
2 <= n <= 100m == roads.lengthn - 1 <= m <= (n * (n - 1) / 2)0 <= a_i, b_i <= n - 1a_i != b_i- The graph is guaranteed to be connected and each pair of nodes may have at most one direct road.
names.length == nnames[i].length == 3names[i]consists of upper-case English letters.- There can be two cities with the same name.
1 <= targetPath.length <= 100targetPath[i].length == 3targetPath[i]consists of upper-case English letters.
Follow up: If each node can be visited only once in the path, What should you change in your solution?
Solution
Approach: DP over (Step, City) with Back Pointers
A path here may revisit cities, so it is simply a sequence of cities where each consecutive pair is joined by a road. Its edit distance is the number of positions i where names[path[i]] != targetPath[i], and each position only depends on which city is used there. That makes a step-by-step DP natural.
Let f[i][j] be the smallest edit distance of a path for targetPath[0..i] that ends at city j:
f[0][j]is0ifnames[j] == targetPath[0], else1.f[i][j] = min over neighbors k of j of f[i - 1][k], plus1ifnames[j] != targetPath[i].
To return the path itself, remember in prev[i][j] which neighbor k gave the minimum. At the end, pick the city j with the smallest f[m - 1][j] and follow prev backwards from step m - 1 down to step 0.
Several paths can tie for the minimum (Example 1 lists three); any of them is accepted. Since the graph is connected and has at least two cities, every city has a neighbor, so every state is reachable.
Follow-up (no repeated cities): the state would also need the set of visited cities, which is exponential in general; the simple DP above relies on paths being allowed to revisit.
Complexity: O(m * (n + E)) time, where m = targetPath.length and E is the number of roads (each road is looked at twice per step), and O(m * n) extra space for f and prev.
class Solution:
def mostSimilar(self, n: int, roads: List[List[int]], names: List[str], targetPath: List[str]) -> List[int]:
g = [[] for _ in range(n)]
for a, b in roads:
g[a].append(b)
g[b].append(a)
m = len(targetPath)
INF = float("inf")
# f[i][j]: smallest edit distance of a path for targetPath[0..i] that ends at city j
f = [[INF] * n for _ in range(m)]
prev = [[-1] * n for _ in range(m)] # the city before j in that best path
for j in range(n):
f[0][j] = int(names[j] != targetPath[0])
for i in range(1, m):
for j in range(n):
cost = int(names[j] != targetPath[i])
for k in g[j]:
if f[i - 1][k] + cost < f[i][j]:
f[i][j] = f[i - 1][k] + cost
prev[i][j] = k
# Start from the best last city and follow prev back to the first step.
city = min(range(n), key=lambda j: f[m - 1][j])
path = [0] * m
for i in range(m - 1, -1, -1):
path[i] = city
city = prev[i][city]
return path