Find longest cycle in directed graph. A cycle is a close path in graph. For example below given directed graph contains a cycle of maximum length of 5 starting from vertex 0, 1, 2 ,3, 4, 0 . Another cycle of length 3 in the graph is 0 1 2 0 . The program should return longest cycle’s length.

Find longest cycle in directed graph

Find longest cycle in directed graph

We know that Floyd-Warshall algorithm finds all pair shortest path in directed graph. In Floyd-Warshall we initially set dist[u][v] = ∞ and dist[v][v] = 0. It means that distance between u and v is infinity and distance to a vertex v to itself is 0. To find a cycle we need to modify dist[v][v] to infinity. This means that from v, we want the shortest path to v, which is the same as finding the shortest cycle which includes vertex v.  ( Ref:

After applying Floyd-Warshall , find max of dist[i][j] where i == j. The maximum value of dist[i][j] where i==j would be the longest cycle in the given graph.

Note: To find the max dist[i][j] where i == j, discard the value of infinite distance. Let us see below modified Floyd-Warshal algorithm to find longest cycle in directed graph.

Related Contents to follow