Search code examples
algorithmtopological-sortconnected-components

Doing topological sort using strongly connected components to find cycles (digraph)


From the little I understand, one way of doing topological sorting if you have a readymade efficient black-box method for strongly connected components would be:

(assumption - no self loops)

  1. run strongly connected components
  2. if you have one or more components of size > 1 then this graph has cycles.
  3. else (there are only 1 sized components in the graph) it's a DAG, congrats!
  4. if it's a DAG run topological sort, else complain that you can't do it.

Regardless of efficiency, is the above a "technically correct" way to do topological sorting?

I just want to make sure I understand things correctly.


Solution

  • Yes, it's technically correct, because a digraph without self-loops is acyclic (i.e., topologically sortable) iff all strong components have size 1. The most common topological sorts do cycle detection as an easy byproduct, though.