Instack is sufficient to check cycle or not

why cant we just check instack, like if it is present in stack already means we have visited that node and cycle exist

here my code, I only checked instack value

During the dfs traversal, you push elements in the stack which are currently active. It means that you are currently exploring the subgraph of that node. Once you are done exploring it’s subgraph, you pop it out of the stack. If now you again discover that vertex, it will not be present in the stack but you have already visited that vertex. Hence, you should always check for cycle using the visited list.
Hope this helps.

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

could u please check my code , is my code correct or not ?


thanks