I need to find the longest cycle in a directed graph using DFS.
I once saw this Wikipedia article describing the way of doing this, and I think it approached the pro
I have an answer explaining an easy way to find all cycles in a directed graph using Python and networkX in another post. Finding all cycles in a directed graph
The solution will output a list containing all cycles of the directed graph.
You can use this output to find the longest cycle ans it is shown bellow:
import networkx as nx
# Create Directed Graph
G=nx.DiGraph()
# Add a list of nodes:
G.add_nodes_from(["1","2","3","4","5","6","7","9"])
# Add a list of edges:
G.add_edges_from([("7","9"),("1","2"),("2","3"),("3","1"),("3","4"),("4","5"),("5","1"),("5","6"),("6","7"),("7","2")])
#Return a list of cycles described as a list o nodes
all_cycles = list(nx.simple_cycles(G))
#Find longest cycle
answer = []
longest_cycle_len = 0
for cycle in all_cycles:
cycle_len = len(cycle)
if cycle_len>longest_cycle_len:
answer =cycle
longest_cycle_len = cycle_len
print "Longest Cycle is {} with length {}.".format(answer,longest_cycle_len)
Answer: Longest Cycle is ['3', '4', '5', '6', '7', '2'] with length 6.
If you find it interesting upvote up the original answer too. It is an old discussion with many answers and it will help bringing the new solution up.