I have spent lots of time on this issue. However, I can only find solutions with non-recursive methods for a tree: Non recursive for tree, or a recursive method for the graph, Recursive for graph.
And lots of tutorials (I don't provide those links here) don't provide the approaches as well. Or the tutorial is totally incorrect. Please help me.
Updated:
It's really hard to describe:
If I have an undirected graph:
1
/ | \
4 | 2
3 /
1-- 2-- 3 --1 is a cycle.
At the step: 'push the neighbors of the popped vertex into the stack', what's the order in which the vertices should be pushed?
If the pushed order is 2
, 4
, 3
, the vertices in the stack are:
| |
|3|
|4|
|2|
_
After popping the nodes, we get the result: 1 -> 3 -> 4 -> 2
instead of 1--> 3 --> 2 -->4
.
It's incorrect. What condition should I add to stop this scenario?