Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use DFS to find cycles in an undirected graph and topological sorting to find cycles in a directed graph?

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?

like image 404
Spandan Avatar asked May 27 '13 19:05

Spandan


People also ask

Why do we use DFS in topological sort?

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'.

Can DFS detect cycle in undirected graph?

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.

Is DFS for directed or undirected 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.

Can DFS be used to find cycles?

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.


1 Answers

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!

like image 153
templatetypedef Avatar answered Sep 20 '22 00:09

templatetypedef