如果我有一个前导字典用于生成单个方向图,例如:
{'A': [], 'B': ['A'], 'C': ['B'], 'D': ['B', 'C'], 'E': ['D']}
我怎么能:
1)找到从A点到E点的所有可能路径并打印出来?
谢谢!
以下代码粘贴:
代码澄清:
G是元组的元组,内部元组是以一种方式连接的顶点对:((开始,结束)(开始,结束))
是开始节点
e是结束节点
def dfs_stack(G,s,e):
stack = [s]
vertices = set([j for t in G for j in t])
visited = dict([(v, False) for v in vertices])
predecessor = dict([(v, []) for v in vertices])
while stack:
u = stack.pop()
if visited[u] == False:
visited[u] = True
for w in get_neighbors(u, G):
if visited[w] == False:
predecessor[w].append(u)
stack.append(w)
elif (visited[w] == True and w != e):
return 'CYCLICAL GRAPH'
return predecessor_to_path(predecessor,s, e)
def predecessor_to_path(pdict, s, end, l=[]):
l.append(end)
if end == s:
return l
else:
for p in pdict[end]:
return predecessor_to_path(pdict, s, p, l)
目前,这只返回最短路径。有关如何修改predecessor_to_path以返回所有路径的任何想法吗?
答案 0 :(得分:1)