查找从一个顶点到另一个顶点的所有路径

时间:2019-03-18 23:44:45

标签: python recursion path

尝试查找从起始顶点到结束顶点的所有可能路径。这是我到目前为止所拥有的。

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)。 adj_list是图的邻接列表,因此在列表的index [i]处,具有通过一条边连接到i的所有顶点的列表(无是该边的权重)

输入为

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?

2 个答案:

答案 0 :(得分:1)

与代码非常相似的逻辑,但已清理干净,这是因为Python可以检查项目是否在列表中,而不用使用单独的'U'或'D'数组。

ajs =  [[(1, None), (2, None)], [(0, None), (2, None)], [(1, None), (0, None)]]

def paths(node, finish):
    routes = []

    def step(node, path):
        for nb,_ in ajs[node]:

            if nb == finish:
                routes.append( path + [node, nb] )

            elif nb not in path:
                step(nb, path + [node])

    step(node, [])
    return routes

print paths(0,2)

答案 1 :(得分:0)

这是您的代码的一种变体,可以得到所需的答案。也就是说,这是解决问题的一种令人困惑的方法。在我看来,该算法正在使用两个递归函数进行求解时,正在散布在两个函数中。

xlist.add(x); 
im = this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), "right");

am = this.getActionMap();
am.put("right", ka);

// **** the comment below is incorrect ****
//only prints out zero - should print out ascending values of x as I hold down the right arrow key
System.out.println(ka.getNextX(xlist));  

例如,这是一个替代实现:

def main():
    adj_list = [
        [(1, None), (2, None)],
        [(0, None), (2, None)],
        [(1, None), (0, None)],
    ]
    paths = sorted(all_paths(adj_list, 0, 2))
    print(paths)

def all_paths(adj_list, source, destination):
    paths = []
    for neighbour, _ in adj_list[source]:
        pth = [source, neighbour]
        if neighbour == destination:
            paths.append(pth)
        else:
            node = finder(
                adj_list,
                neighbour,
                ['U'] * len(adj_list),
                pth,
                destination,
            )
            paths.append(pth + [node])
    return paths

def finder(adj_list, current, state, pth, end):
    for neighbour, _ in adj_list[current]:
        if neighbour == end:
            state[neighbour] = 'D'
            return neighbour
        elif state[neighbour] == 'U':
            state[neighbour] = 'D'
            return finder(adj_list, neighbour, state, pth, end)

main()