Skip to content

Commit 76f15c1

Browse files
authored
Create the-most-similar-path-in-a-graph.py
1 parent afe5c82 commit 76f15c1

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Time: O(n^2 * m), m is the length of targetPath
2+
# Space: O(n * m)
3+
4+
class Solution(object):
5+
def mostSimilar(self, n, roads, names, targetPath):
6+
"""
7+
:type n: int
8+
:type roads: List[List[int]]
9+
:type names: List[str]
10+
:type targetPath: List[str]
11+
:rtype: List[int]
12+
"""
13+
adj = [[] for _ in xrange(n)]
14+
for u, v in roads:
15+
adj[u].append(v)
16+
adj[v].append(u)
17+
18+
dp = [[0]*n for _ in xrange(len(targetPath)+1)]
19+
for i in xrange(1, len(targetPath)+1):
20+
for v in xrange(n):
21+
dp[i][v] = (names[v] != targetPath[i-1]) + min(dp[i-1][u] for u in adj[v])
22+
23+
path = [dp[-1].index(min(dp[-1]))]
24+
for i in reversed(xrange(2, len(targetPath)+1)):
25+
for u in adj[path[-1]]:
26+
if dp[i-1][u]+(names[path[-1]] != targetPath[i-1]) == dp[i][path[-1]]:
27+
path.append(u)
28+
break
29+
return path[::-1]

0 commit comments

Comments
 (0)