Transitive closure of a graph using Floyd Warshall Algorithm (original) (raw)

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

Try It Yourselfredirect icon

**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. C++ `

// C++ program to find Transitive closure of // a graph using Floyd Warshall Algorithm #include <bits/stdc++.h> using namespace std;

vector<vector> transitiveClosure(vector<vector> graph) { int n = graph.size();

vector<vector<int>> ans(n, vector<int>(n, 0));

// Copy the graph into resultant matrix
for (int i=0; i<n; i++) {
  for (int j=0; j<n; j++) {
    ans[i][j] = graph[i][j];
  }
}

// Transtive closure of (i, i) will always be 1 
for (int i=0; i<n; i++) ans[i][i] = 1;

// Apply floyd Warshall Algorithm
// For each intermediate node k
for (int k=0; k<n; k++) {
    for (int i=0; i<n; i++) {
        for (int j=0; j<n; j++) {
          
            // Check if a path exists between i to k and 
            // between k to j.
            if (ans[i][k]==1 && ans[k][j]==1) {
                ans[i][j] = 1;
            }
        }
    }
}

return ans;

}

int main() { int n = 4; vector<vector> graph = {{0, 1, 1, 0}, {0, 0, 1, 0}, {1, 0, 0, 1}, {0, 0, 0, 0}}; vector<vector> ans = transitiveClosure(graph);

for (int i=0; i<n; i++) {
  for (int j=0; j<n; j++) {
    cout << ans[i][j] << " ";
  }
  cout << endl;
}

return 0;

}

Java

// Java program to find Transitive closure of // a graph using Floyd Warshall Algorithm import java.util.*;

class GfG {

static ArrayList<ArrayList<Integer>> transitiveClosure(int[][] graph) {
    int n = graph.length;
    ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
    
    // Copy the graph into resultant matrix
    for (int i = 0; i < n; i++) {
        ArrayList<Integer> row = new ArrayList<>();
        for (int j = 0; j < n; j++) {
            row.add(graph[i][j]);
        }
        ans.add(row);
    }

    // Transtive closure of (i, i) will always be 1 
    for (int i = 0; i < n; i++) ans.get(i).set(i, 1);

    // Apply floyd Warshall Algorithm
    // For each intermediate node k
    for (int k = 0; k < n; k++) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {

                // Check if a path exists between i to k and 
                // between k to j.
                if (ans.get(i).get(k) == 1 && ans.get(k).get(j) == 1) {
                    ans.get(i).set(j, 1);
                }
            }
        }
    }

    return ans;
}

public static void main(String[] args) {
    int n = 4;
    int[][] graph = {{0, 1, 1, 0}, {0, 0, 1, 0}, {1, 0, 0, 1}, {0, 0, 0, 0}};
    ArrayList<ArrayList<Integer>> ans = transitiveClosure(graph);

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            System.out.print(ans.get(i).get(j) + " ");
        }
        System.out.println();
    }
}

}

Python

Python program to find Transitive closure of

a graph using Floyd Warshall Algorithm

Copy the graph into resultant matrix

def transitiveClosure(graph): n = len(graph) ans = [[graph[i][j] for j in range(n)] for i in range(n)]

# Transtive closure of (i, i) will always be 1 
for i in range(n):
    ans[i][i] = 1

# Apply floyd Warshall Algorithm
# For each intermediate node k
for k in range(n):
    for i in range(n):
        for j in range(n):

            # Check if a path exists between i to k and 
            # between k to j.
            if ans[i][k] == 1 and ans[k][j] == 1:
                ans[i][j] = 1

return ans

if name == "main": n = 4 graph = [[0, 1, 1, 0], [0, 0, 1, 0], [1, 0, 0, 1], [0, 0, 0, 0]] ans = transitiveClosure(graph)

for i in range(n):
    for j in range(n):
        print(ans[i][j], end=" ")
    print()

C#

// C# program to find Transitive closure of // a graph using Floyd Warshall Algorithm using System; using System.Collections.Generic;

class GfG {

static List<List<int>> transitiveClosure(int[,] graph) {
    int n = graph.GetLength(0);
    List<List<int>> ans = new List<List<int>>();
    
    // Copy the graph into resultant matrix
    for (int i = 0; i < n; i++) {
        List<int> row = new List<int>();
        for (int j = 0; j < n; j++) {
            row.Add(graph[i, j]);
        }
        ans.Add(row);
    }

    // Transtive closure of (i, i) will always be 1 
    for (int i = 0; i < n; i++) ans[i][i] = 1;

    // Apply floyd Warshall Algorithm
    // For each intermediate node k
    for (int k = 0; k < n; k++) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {

                // Check if a path exists between i to k and 
                // between k to j.
                if (ans[i][k] == 1 && ans[k][j] == 1) {
                    ans[i][j] = 1;
                }
            }
        }
    }

    return ans;
}

static void Main() {
    int n = 4;
    int[,] graph = new int[,] {
        {0, 1, 1, 0},
        {0, 0, 1, 0},
        {1, 0, 0, 1},
        {0, 0, 0, 0}
    };
    List<List<int>> ans = transitiveClosure(graph);

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            Console.Write(ans[i][j] + " ");
        }
        Console.WriteLine();
    }
}

}

JavaScript

// JavaScript program to find Transitive closure of // a graph using Floyd Warshall Algorithm

function transitiveClosure(graph) { let n = graph.length; let ans = new Array(n).fill(0).map(() => new Array(n).fill(0));

// Copy the graph into resultant matrix
for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
        ans[i][j] = graph[i][j];
    }
}

// Transtive closure of (i, i) will always be 1 
for (let i = 0; i < n; i++) ans[i][i] = 1;

// Apply floyd Warshall Algorithm
// For each intermediate node k
for (let k = 0; k < n; k++) {
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < n; j++) {

            // Check if a path exists between i to k and 
            // between k to j.
            if (ans[i][k] === 1 && ans[k][j] === 1) {
                ans[i][j] = 1;
            }
        }
    }
}

return ans;

}

let n = 4; let graph = [[0, 1, 1, 0], [0, 0, 1, 0], [1, 0, 0, 1], [0, 0, 0, 0]]; let ans = transitiveClosure(graph);

for (let i = 0; i < n; i++) { let row = ""; for (let j = 0; j < n; j++) { row += ans[i][j] + " "; } console.log(row); }

`

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: