568. The Most Similar Path in a Graph
Given a set of n cities connected by m bidirectional roads, represented as roads[i] = [ai, bi], where ai and bi denote two directly connected cities. Each city has a three-letter uppercase English name, provided in an array called names.
You can start at any city and travel to another city y (where y ≠x) following the given roads. The cities and roads together form a connected undirected graph.
Given a targetPath array consisting of city names, your task is to determine a valid path in the graph that matches the length of targetPath while minimizing the edit distance.
The edit distance between two paths is calculated by counting the number of indices where the names in the chosen path differ from those in targetPath.
Return a sequence of city indices representing the path that minimizes the edit distance. The path should be valid, meaning that each consecutive pair of cities in the path must be directly connected. If multiple paths have the same minimal edit distance, return any of them. The output will be true if the sequence returned is correct otherwise it will be false.
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:
Possible valid paths include [0,2,4,2], [0,3,0,2], and [0,3,1,2].
[0,2,4,2] corresponds to ["ATL","LAX","HND","LAX"], which has an edit distance of 1 with targetPath.
[0,3,0,2] corresponds to ["ATL","DXB","ATL","LAX"], which also has an edit distance of 1.
[0,3,1,2] corresponds to ["ATL","DXB","PEK","LAX"], with an edit distance of 1.
All are valid answers since they yield the minimum edit distance.
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:
Since no city names match those in targetPath, the minimum possible edit distance is 8, meaning every position in the path is different from targetPath.
Now Your Turn!
Pick the correct output for the given inputInput: 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"]Â Â
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 2 ≤ n ≤ 100
- m == roads.length
- n - 1 ≤ m ≤ (n * (n - 1) / 2)
- 0 ≤ ai, bi ≤ n - 1
- ai ≠bi
- The graph is guaranteed to be fully connected, meaning every city is reachable.
- Each pair of cities has at most one direct road.
- names.length == n
- names[i] consists of exactly three uppercase English letters.
- There can be multiple cities with the same name.
- 1 ≤ targetPath.length ≤ 100
- targetPath[i] is always a three-letter uppercase string.