查找有向图中的所有循环

时间:2016-07-20 13:35:16

标签: python graph path cycle

我正在使用以下python代码来查找图中的任何循环,但它不会返回正确的结果

for node in graph:
    new_path=node
    path = node
    for adjacent in graph.get(node, []):
        if not adjacent in new_path:
            new_path = list(path)
            new_path.append(adjacent)
        else:
            print (new_path)

你能帮我找一下图中的任何周期吗?

输入样本:

graph = {
    '181': set(['284','248','247','350']),
    '350': set(['400', '401']),
    '400': set(['181', '654'])
}

期望的输出:

181 350 400 181

我的代码目前没有输出任何内容。

0 个答案:

没有答案
相关问题