7

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,

asked Dec 18, 2012 at 19:37

2 Answers 2

7

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!

answered Dec 18, 2012 at 19:41

1 Comment

amazing, thanks, I learned it the way that orders of which i visit the node matters, i guess the textbook differs in that assumption.
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.

answered Dec 19, 2012 at 17:31

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.