# Find longest cycle in directed graph

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*

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: https://www.quora.com/Can-Floyd-Warshall-algorithm-be-used-to-find-shortest-cycle-in-an-undirected-graph)

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.
*

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
#include<iostream> #include<cstring> using namespace std; #define V 7 #define inf 999999 // adjacency matrix as distance matrix for the graph int dist[V][V] ={{inf, 1, inf, inf, inf, inf,inf}, { inf, inf, 1, inf, inf, 1, inf}, { 1, inf, inf, 1, inf, inf, inf}, { inf, inf, inf, inf, 1, inf, inf}, { 1, inf, inf, inf, inf, inf, 1}, { inf, inf, inf, inf, inf, inf, 1}, { inf, inf, inf, inf, inf, inf, inf}, }; int main () { // run Floyd-Warshal algo on graph for (int k = 0; k < V; k++) { for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (dist[i][j] > dist[i][k] + dist[k][j]) dist[i][j] = dist[i][k] + dist[k][j]; } } } // print minimum dist[v][v] int maxlength = -1; for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (i == j) { if (maxlength < dist[i][j] && dist[i][j] != inf) maxlength = dist[i][j]; } } } cout << maxlength << endl; return 0; } |

## Leave a Reply