10

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?

lastr2d2
  • 3,604
  • 2
  • 22
  • 37
Dhananjay Tyagi
  • 113
  • 1
  • 1
  • 9
  • 1
    I also had similar confusion, but now I am clear: DFS: go deeper and deeper along with printing. Topological sort: pick each unvisited vertix and print its dependent first before printing parent(itself). – Manish gour May 31 '20 at 02:40

4 Answers4

9

Well, topological sorting is a specific order of the nodes of a directed acyclic graph, which can be achieved by depth-first search. Besides depth-first search, there are other methods to find the topological order, like the Kahn's algorighm.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
3

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.

cong
  • 31
  • 1
1

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.

0

If you want to get a clear idea, you can try the following problem.

https://onlinejudge.org/index.php?option=onlinejudge&Itemid=8&page=show_problem&category=0&problem=1246&mosmsg=Submission+received+with+ID+25820106

At first, you might jump into doing straightforward DFS, but it fails in some cases.

For eg: DFS fails in the following test case:

5 4 (no. of vertices and edges respectively)

(Description of the edges)

1 2

2 3

1 4

4 3