Skip to content

Instantly share code, notes, and snippets.

@anil477
Created July 25, 2017 04:52
Show Gist options
  • Save anil477/065251ccce5e2fcca75ce49ea80ec42e to your computer and use it in GitHub Desktop.
Save anil477/065251ccce5e2fcca75ce49ea80ec42e to your computer and use it in GitHub Desktop.
Transitive Closure of a Graph using DFS
// Given a directed graph, find out if a vertex v is reachable from another vertex u for all vertex pairs (u, v) in the given graph.
import java.util.LinkedList;
class Graph
{
int V; // No. of vertices
boolean [][]tc; // To store transitive closure
LinkedList<Integer> adj[]; // array of adjacency lists
public Graph(int V)
{
this.V = V;
adj = new LinkedList[V];
tc = new boolean[V][V];
for (int i=0; i<V; i++)
{
tc[i] = new boolean[V];
adj[i] = new LinkedList<Integer>();
for(int j =0 ;j < V; j++)
tc[i][j] = false;
}
}
// function to add an edge to graph
public void addEdge(int v, int w)
{
adj[v].addLast(w);
}
// prints transitive closure matrix
public void transitiveClosure()
{
// Call the recursive helper function to print DFS
// traversal starting from all vertices one by one
for (int i = 0; i < V; i++)
DFSUtil(i, i); // Every vertex is reachable from self.
for (int i=0; i<V; i++)
{
for (int j=0; j<V; j++)
System.out.print( tc[i][j] + " ");
System.out.println();
}
}
public void DFSUtil(int s, int v)
{
// Mark reachability from s to t as true.
System.out.println(" s: " + s + " v: " + v);
tc[s][v] = true;
for (Integer i : adj[v])
if (tc[s][i] == false)
DFSUtil(s, i);
}
public static void main(String[] args)
{
// Create a graph given in the above diagram
Graph g = new Graph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
System.out.println( "Transitive closure matrix is ");
g.transitiveClosure();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment