For undirected graphs , if we need to find a cycle , we use depth-first search as described in this older question,which is a well known method and also optimal .
But for directed graph, this other question suggests using topological sorting.
My question is, why can't we use the same technique we use for undirected graphs, to check for cycles in directed graph? I've thought of various cases and the algorithms always seem to agree.
Can anyone come up with some example directed graph where DFS fails to find a cycle but topological sorting does?
In DFS, we print a vertex and then recursively call DFS for its adjacent vertices. In topological sorting, we need to print a vertex before its adjacent vertices. For example, in the given graph, the vertex '5' should be printed before vertex '0', but unlike DFS, the vertex '4' should also be printed before vertex '0'.
Find cycle in undirected Graph using DFS:Depth First Traversal can be used to detect a cycle in a Graph. There is a cycle in a graph only if there is a back edge present in the graph.
DFS can be used on directed graphs just as well as on undirected graphs. Given a vertex, in both cases it finds all vertices reachable from it.
Predominantly DFS is used to find a cycle in graphs and not BFS. Any reasons? Both can find if a node has already been visited while traversing the tree/graph. In directed graphs, only DFS can be used to detect a cycle; but in Undirected graphs both can be used.
It seems like your question is the following: can you use depth-first search to detect cycles in an undirected graph, or should you use topological sort instead?
The answer is that both approaches will work. If there is a cycle in a directed graph, then you can detect this by running a depth-first search over the graph. As soon as you start the search from a node in the cycle, you are guaranteed to eventually discover the cycle.
It turns out that topological sorting and DFS are closely related in the following way: if you run a DFS in a graph and don't find a cycle, then the reverse order in which you marked each node as fully-explored will give a topological sort of the graph. In other words, the solution of "use topological sort" and the solution of "use DFS" can be thought of as extremely similar algorithms, since one way to implement topological sorting is with DFS.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With