试图找到从起始顶点到结束顶点的所有可能路径。这是我到目前为止。
def all_paths(adj_list, source, destination):
paths = []
for neighbour,_ in adj_list[source]:
path = [source,neighbour]
state = ['U'] * len(adj_list)
state[neighbour] = 'D'
path = finder(adj_list, neighbour, state, path, destination)
paths.append(path)
return paths
def finder(adj_list, current, state, path, end):
for neighbour,_ in adj_list[current]:
if neighbour == end:
path.append(neighbour)
return path
if state[neighbour] == 'U':
state[neighbour] = 'D'
path.append(finder(adj_list, neighbour, state, path, end))
return path
状态数组是为了确保没有顶点被访问两次(U 未被发现,D 被发现)。通过边连接到 i (Nones 是所述边的权重)
输入是
adj_list = [[(1, None), (2, None)], [(0, None), (2, None)], [(1, None), (0, None)]]
print(sorted(all_paths(adj_list, 0, 2)))
预期的输出是
[[0, 1, 2], [0, 2]]
我的输出是
[[0, 1, 2, [...]], [0, 2, 2, [...], [...]]]
不确定我是如何得到这些点和第二条路径中重复的 2 的?
拉丁的传说
慕斯王
相关分类