Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 遍历所有顶点并使用DFS返回开始顶点_Python - Fatal编程技术网

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

Python 遍历所有顶点并使用DFS返回开始顶点,python,Python,我试图在Python中实现DFS图遍历,其中我必须从顶点1开始,访问所有顶点,并在开始顶点(即顶点1)结束搜索。具有顶点边列表的图形为: {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中实现这

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

{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中实现这一点不确定这是否是您想要的从左到右的深度优先:

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]

让我们看看你已经拥有了什么!是的。同意hivert的意见。因此,我们可以更好地了解您的问题所在。由于6未连接到7,因此无法从6转到顶点7。@user3293224从8转到7。此时,您已经在回溯。