Trying to find all cycles in a directed graph, via DFS. But got an issue.
Issue
When there are multiple cycles between 2 nodes, sometimes only the longest one can be detected, the shorter one is skipped.
This is due to when a node is visited, I will skip it, thus that shorter cycle is skipped. But, if I don't skip visited node, the DFS search will repeat forever.
Example
Graph:
1 -> [2, 4]
2 -> [3]
3 -> [4]
4 -> [1]
There are 2 cycles between 1 and 4:
- (A) 1 -> 2 -> 3 -> 4 -> 1
- (B) 1 -> 4 -> 1
Cycle B can't be detected, if A is detected first, because 4 will be skipped due to visited, and it never goes back to 1.
Current ideas
- One possible solution is to start from every node, even it's already visited. But I want a better solution.
- Calculate & remember hash of path, skip only when the same hash exists? That would take some memory, right? And, there are still possibility 2 different path with the same hash lead to the same node, it can't solve the problem entirely.
Any idea?
Credits: https://www.hackerearth.com/practice/notes/finding-all-elementry-cycles-in-a-directed-graph/
We want to find distinct cycles. Hence, we need to visit vertices in some order. In that order, we need to find cycles starting from that vertex and the cycle should not contain any vertices that are before the starting vertex in the ordering. How to obtain that ordering? The words
topological mannerin one of the comments above is ambiguous withtopological sortwhich is not the case. I think we can pick an ordering as simple as vertex number like 0,1,2,..,v. Let us say we wish to find a cycle starting from 2. To avoid finding of duplicate cycles, we will not use vertex 0 and 1. If there is any cycle that consists of edge from 2 to 1 or 2 to 0, it would already have been considered when finding cycles starting from 0 or 1.Let me introduce a concrete reference that will help you with the task. It is Johnson's algorithm. Apparently, it is the fastest way to accomplish the task.
On page 3, it mentions:
You can also watch this youtube video for more understanding.
I think this information is acceptable.