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

#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;
}


Related Contents to follow