VOOZH about

URL: https://www.geeksforgeeks.org/dsa/transitive-closure-of-a-graph/

⇱ Transitive closure of a graph using Floyd Warshall Algorithm - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Transitive closure of a graph using Floyd Warshall Algorithm

Last Updated : 23 Jul, 2025

Given a directed graph, determine if a vertex j is reachable from another vertex i for all vertex pairs (i, j) in the given graph. Here reachable means that there is a path from vertex i to j. The reach-ability matrix is called the transitive closure of a graph.

Example:

Input: Graph = [[0, 1, 1, 0], [0, 0, 1, 0], [1, 0, 0, 1], [0, 0, 0, 0]]
👁 Untitled-Diagram-(1)

Output:
1 1 1 1
1 1 1 1
1 1 1 1
0 0 0 1

Approach:

The idea is to use the Floyd-Warshall algorithm to find the transitive closure of a directed graph. We start by initializing a result matrix with the original adjacency matrix and set all diagonal elements to 1 (since every vertex can reach itself). Then for each intermediate vertex k, we check if vertex i can reach vertex j either directly or through vertex k. If a path exists from i to k and from k to j, then we mark that i can reach j in our result matrix.

Step by step approach:

  1. Initialize result matrix with input graph and set all diagonal elements to 1.
  2. For each intermediate vertex, check all possible vertex pairs.
  3. If vertex i can reach intermediate vertex and intermediate vertex can reach vertex j, mark that i can reach j. This iteratively builds paths of increasing length through intermediate vertices.
  4. Return the final matrix where a value of 1 indicates vertex i can reach vertex j.

Output
1 1 1 1 
1 1 1 1 
1 1 1 1 
0 0 0 1 

Time Complexity: O(v^3) where v is number of vertices in the given graph.
Auxiliary Space: O(v^2) to store the result.

Related Article:

Comment
Article Tags:
Article Tags: