简体   繁体   English

Python.DFS图遍历,正确output?

[英]Python. DFS graph traversal, correct output?

I'm currently getting to grips with graph traversal in Python.我目前正在研究 Python 中的图形遍历。

Given the following graph:给定下图:

在此处输入图像描述

Implemented using this dictionary:使用这个字典实现:


graph = {'0': set(['1', '2', '3']),
         '1': set(['0','2']),
         '2': set(['0','1','4']),
         '3': set(['0']),
         '4': set(['2'])}

Am I correct in thinking a depth first search traversal beginning from node 0 should return [0,1,2,4,3] ?我认为从节点 0 开始的深度优先搜索遍历应该返回[0,1,2,4,3]是否正确?

My dfs function returns [0,3,1,2,4] and so I am wondering if I have something wrong in my implementation:我的 dfs function 返回[0,3,1,2,4]所以我想知道我的实现是否有问题:

def dfs(graph, node,visited=None):
    if visited is None:
        visited=set()
        
    if node not in visited:
        print (node,end=' ')
        visited.add(node)
        
        for neighbour in graph[node]:
            dfs(graph,neighbour,visited=visited)

dfs(graph,'0')

Help and advice appreciated.帮助和建议表示赞赏。

No you aren't.不,你不是。

You would be right to say that traversal order COULD be [0,1,2,4,3] .你说遍历顺序可以是[0,1,2,4,3]是对的。 Not that it should.不是应该的。 The only thing you know about traversal order is that you explore, among everything explorable, first the descendant of the last explored node.关于遍历顺序,你唯一知道的是,在所有可探索的事物中,首先探索最后一个探索节点的后代。 But among those, nothing tells you any order.但在这些之中,没有任何东西告诉你任何顺序。

And the implementation you've chosen make that extra clear, since set in python don't have a specific order (but even if you'd chosen list instead of set, and written an implementation that, among the child of the most recently explored nodes, explores the first child of the list, leading indeed to [0,1,2,4,3] , that would be just your implementation, not a rule about DFS. Nothing says that you should favor one child against another; or, to be more accurate, since you have to choose one, nothing says in which order. That is totally implementation dependent).而且您选择的实现更加清楚,因为 python 中的set没有特定顺序(但即使您选择列表而不是设置,并编写了一个实现,在最近探索的子项中节点,探索列表的第一个孩子,确实导致[0,1,2,4,3] ,这只是你的实现,而不是关于 DFS 的规则。没有人说你应该偏爱一个孩子而不是另一个孩子;或者,更准确地说,因为你必须选择一个,所以没有说明顺序。这完全取决于实现)。

So from your graph, starting from 0, a DFS traversal order could be any of所以从你的图中,从 0 开始,DFS 遍历顺序可以是任何

0,1,2,4,3
0,2,1,4,3
0,2,4,1,3
0,3,1,2,4
0,3,2,1,4
0,3,2,4,1

(Plus those I may have forgotten) (加上我可能忘记的那些)

Never mind.没关系。

I realise my error was due to how I had initiated the graph.我意识到我的错误是由于我启动图表的方式造成的。 I mistakenly passed in sets.我错误地通过了集合。 Using the following seems to produce the expected results:使用以下内容似乎会产生预期的结果:

graph = {'0': ['1', '2', '3'],
         '1': ['0','2'],
         '2': ['0','1','4'],
         '3': ['0'],
         '4': ['2']}

dfs(graph, '0')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM