
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,
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:
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!