6

enter image description here

Given the above graph, the DFS traversal with a stack gives me the folowing path...

1-2-3-4-5-6

Is the above path valid? Does there exists another path? (my textbook gives me 1-2-3-6-4-5)

I don't have enough rep to post images over at computer science stack so I had to resort to asking here, not sure if it fits; if it doesn't I am happy to delete it afterwards.

Thanks,

user1234440
  • 22,521
  • 18
  • 61
  • 103

2 Answers2

6

You have listed a perfectly valid DFS traversal of the graph, and the textbook is giving you another totally legal DFS traversal of the graph. There can be many depth-first traversals of the same graph (in fact, there's often exponentially many of them), so if you don't get the same one as your textbook that's not an immediate cause for alarm.

Here are some other orderings:

1 2 5 4 3 6
3 1 6 2 5 4
5 4 2 3 1 6
...

However, if there are some other rules about how nodes ought to be visited (for example, always visiting connected nodes in ascending or descending order), then a DFS search will always produce the same output.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • amazing, thanks, I learned it the way that orders of which i visit the node matters, i guess the textbook differs in that assumption. – user1234440 Dec 18 '12 at 19:43
1

The output you describe is not a path, it's the order in which DFS visits the nodes. A path is a list of nodes where each node is connected to the previous and next node.

The output of the DFS traversal can also be seen as a DFS traversal tree, which in your case corresponds to:

1 - 2 - 3 - 4 - 5
        |
        6

The textbook tree is

1 - 2 - 3 - 6 
        |
        4 - 5

You can get many different DFS trees, because at each point where you have a choice, you can decide where to go first. In your examples, from node 3 you can go to node 4 or node 6, and the different outputs are due to the different choices.

Dejan Jovanović
  • 2,085
  • 1
  • 16
  • 22