This works for undirected graphs also right?

This works for undirected graphs also right ? Please clear this.

@pswaldia1
no, for directed graph using dfs, the concept of back - edge is used.
So if you will use it for the undirected graph then you will miss the cases when there is cycle according to undirected graph.

for eg:- consider a graph with edges(draw it on paper and then see):- 1->2, 1->3, 2->4, 3->4. In this case it will be False but for undirected it will be true.

if i have well understood your graph , the edges are (1, 2) (2, 1) (2, 4) (4, 2) (1, 3) (3, 1) (3, 4) (4, 3) . so in this according to the concept taught in the video , the function will return true . let me dry run the approach. starting at 1 we will move to (suppose) 2 then to 3 then to 4 and then again to 1. nodes from 1 to 4 all are in the maintained stack array , and 1 is visited so the answer returned will be true which is correct for the given graph. Correct me if i am wrong. and i think you answered for the question : will the approach for undirected graph work for directed graph or not. but my question was reverse.

@pswaldia1
If you apply the same algorithm for undirected graph. let say for eg:- (1,2) and (2,1) are inserted in our adjacency list. So start from 1 then reach 2. Then from 2 we have a edge to 1 also. But then you still have to add the condition of parent!=child (like we do in undirected graph dfs algo) because there is a edge from 2 to 1 also. Otherwise if you don’t add this condition then the algo will true for this graph also.
So there remains no benefit of using this Algorithm there because you will we doing extra work of maintaining the stack for the path. It will be just a redundant work.