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 <= 100
m == roads.length
n - 1 <= m <= (n * (n - 1) / 2)
0 <= ai, bi <= n - 1
ai != bi
- The graph is guaranteed to be connected and each pair of nodes may have at most one direct road.
names.length == n
names[i].length == 3
names[i]
consists of upper-case English letters.- There can be two cities with the same name.
1 <= targetPath.length <= 100
targetPath[i].length == 3
targetPath[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
This problem is a classic example of using Dynamic Programming on Graphs. The goal is to find a path of the same length as targetPath
with the minimum edit distance, where the edit distance is the number of positions where the city name in the path differs from the target.
We can use DP where dp[i][city]
is the minimum edit distance to reach city
at position i
in the path. For each position, we try all possible cities and for each, try all possible previous cities that are connected to it. We also keep a parent
table to reconstruct the path.
Steps:
- Build the adjacency list for the graph.
- Initialize
dp
andparent
tables. - For each position in
targetPath
, for each city, update the minimum edit distance from all possible previous cities. - Find the city at the last position with the minimum edit distance and reconstruct the path using the
parent
table.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity Analysis
- ⏰ Time complexity:
O(m * n * d)
wherem
is the length oftargetPath
,n
is the number of cities, andd
is the average degree (max n). - 🧺 Space complexity:
O(m * n)
for the DP and parent tables.