Python. DFS graph traversal, correct output?

Question:

I’m currently getting to grips with graph traversal in Python.

Given the following graph:

enter image description here

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]?

My dfs function returns [0,3,1,2,4] and so I am wondering if I have something wrong in my implementation:

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.

Asked By: r0bt

||

Answers:

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')
Answered By: r0bt

No you aren’t.

You would be right to say that traversal order COULD be [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).

So from your graph, starting from 0, a DFS traversal order could be any of

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)

Answered By: chrslg