[英]Find all paths in graph from A to N
我正在嘗試將以下示例python代碼移植到Java:
def find_all_paths(graph, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
if not graph.has_key(start):
return []
paths = []
for node in graph[start]:
if node not in path:
newpaths = find_all_paths(graph, node, end, path)
for newpath in newpaths:
paths.append(newpath)
return paths
問題是,要停止遞歸的基本情況:
if start == end:
return [path]
它不支持我允許A和N成為同一節點的要求。
例如:
如果我有以下圖 :
A -> [B, C],
B -> [C, E],
C -> [D, A]
我想要A和A之間的所有路徑,我應該得到結果:
A -> B -> C -> A
上面的python代碼只會給我:
A
從A到A的路徑必須經過A的鄰居。因此,實現此目的的一種方法是枚舉所有向外的鄰居:
[[["A"]+y for y in find_all_paths(G,x,"A")] for x in graph["A"]]
對於您的圖形,結果應為
[[['A', 'B', 'C', 'A']], [['A', 'C', 'A']]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.