![]() |
VOOZH | about |
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 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: