Is there a difference between dfs and topological sort? Can topological ordering be achieved without using dfs?

Viewed 10489

I was trying to write code for detecting a cycle in a directed graph and if there is no cycle then return a topological order of the same.

While I was searching for it I came across different techniques like DFS and topological sorting to detect cycle in a directed graph.

Is there any difference between these two?

4 Answers

Topological sort is a DFS-based algorithm on a directed acyclic graph (DAG). Topological ordering is a linear ordering of vertices such that for every directed edge uv, vertex u comes before v in the ordering.

A topological ordering is possible if and only if the graph has no directed cycles. But DFS can be performed on directed or undirected graphs.

Topological sort uses DFS in the following manner:

  1. Call DFS
  2. Note when all edges have been explored (i.e. the finishing times)
  3. After a vertex is finished, insert an identifier at the head of the topological sort L
  4. The completed list L is a topological sort

Run-time: O(V+E)

By nature, the topological sort algorithm uses DFS on a DAG. The DFS properties are crucial for the returned list to appear in correct, topological order. However, as seen in the answers above, yes ordering cannot be achieved without using DFS. Examples are Kahn's algorithm and parallel sorting.

Related