遍历所有顶点并返回到使用DFS开始顶点

时间:2014-02-10 14:31:42

标签: python

我正在尝试在Python中实现DFS图遍历,我必须从顶点1开始并访问所有顶点并在起始顶点(即顶点1)处结束搜索。具有顶点边缘列表的图形为:< / p>

{1: [2, 5, 6, 7],
 2: [1, 3, 4, 8],
 3: [2, 8],
 4: [2, 7],
 5: [1, 6, 8],
 6: [1, 5, 8],
 7: [1, 4, 8],
 8: [2, 3, 5, 6, 7]}

当我从1移动到7时,我的程序弹出8然后搜索变得随意。我正在弹出最后一个元素。我怎样才能在python

中实现它

1 个答案:

答案 0 :(得分:0)

不确定这是否是您想要的(深度优先,从左到右):

def dfs (node, graph, path = None):
    path = path if path else []
    if node in path: return path
    path.append (node)
    for child in graph [node]:
        path = dfs (child, graph, path)
    return path

使用您返回的数据运行它:

[1, 2, 3, 8, 5, 6, 7, 4]