Problem
We have n cities and m bi-directional roads where roads[i] = [ai, bi]
connects city ai with city bi. 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:
| |
Examples
Example 1:
| |
Example 2:
| |
Example 3:
| |
Constraints:
2 <= n <= 100m == roads.lengthn - 1 <= m <= (n * (n - 1) / 2)0 <= ai, bi <= n - 1ai != bi- 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
Method 1 - Dynamic Programming on Graph (Backward DP)
Intuition
We use dynamic programming to find the path of minimum edit distance. For each position in the targetPath and each city, we keep the minimum edit distance to reach that city at that position, and a parent pointer to reconstruct the path. The backward DP (from last position to first) lets us compute costs using future states.
Approach
- Build an adjacency list for the graph.
- Initialize
dp(sizem x n) with large values andparentwith -1. - Set
dp[m-1][i] = 0ifnames[i] == targetPath[m-1]else1for all citiesi. - For
ifromm-2down to0, for each cityuand neighborvofu, updatedp[i][u]usingdp[i+1][v] + cost(u,i)wherecost(u,i)is0ifnames[u] == targetPath[i]else1. Store the chosenvinparent[i][u]. - Choose the start city with minimum
dp[0][city]and reconstruct the path using theparenttable.
Complexity
- ⏰ Time complexity:
O(m * n * d)– For each of themtarget positions we consider up toncities and iterate over their neighbors (average degreed, worst-casen). - 🧺 Space complexity:
O(m * n)– We storedpandparenttables of sizem * n.
Code
| |
| |
| |
| |
| |
| |
| |