0

I have a graph that contains exactly one cycle but I need to sort it using a "topological sort" (of course actual topological sort does not handle cycle). I am wondering how can it be done?

For example:

A -> B
B -> C
C -> D
D -> A

Possible solutions are:

A -> B -> C -> D
B -> C -> D -> A
C -> D -> A -> B
D -> A -> B -> C

I see there is this algorithm as suggested here but it's too overcomplicated for my use case.

Node.JS
  • 1,042
  • 6
  • 44
  • 114
  • 1
    Just do an ordinary topological sort. There are a few [standard approaches](https://en.wikipedia.org/wiki/Topological_sorting) out there. One of the simplest (in my opinion) is to use DFS. Note that when you encounter a cycle, you can simply ignore it. – paddy Jun 23 '22 at 01:22

1 Answers1

2

There are a few approaches and implementations for topological sort. The most intuitive one I have found is to:

  1. Identify nodes with no incoming edges (Can be done through creating an adjacency list and a dictionary containing incoming edge counts for vertices).
  2. Add these to the sorted list
  3. Remove this node from the graph and subtract it from the count of incoming edges for the node
  4. Repeat process until there are no longer any nodes with a count above 0.
  5. If the sorted list is larger than the number of vertices you will know that you have a cycle at this point and can terminate the algorithm.

There are many code samples with various implementations online but this algorithm should help guide the implementation for a basic topological sort.

Poiuy
  • 331
  • 2
  • 6