我正在尝试将以下示例 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']]]
关于python - 查找图中从 A 到 N 的所有路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19581870/