I found the following:
Given a directed graph, find out 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 transitive closure of a graph.
The graph is given in the form of adjacency matrix say ‘graph[V][V]’ where graph[i][j] is 1 if there is an edge from vertex i to vertex j or i is equal to j, otherwise graph[i][j] is 0.
We can calculate the distance matrix dist[V][V] using Floyd Warshall, if dist[i][j] is infinite, then j is not reachable from i, otherwise j is reachable and value of dist[i][j] will be less than V.
// Prints transitive closure of graph[][] using Floyd Warshall algorithm
void transitiveClosure(int graph[][V])
{
/* reach[][] will be the output matrix that will finally have the shortest
distances between every pair of vertices */
int reach[V][V], i, j, k;
/* Initialize the solution matrix same as input graph matrix. Or
we can say the initial values of shortest distances are based
on shortest paths considering no intermediate vertex. */
for (i = 0; i < V; i++)
for (j = 0; j < V; j++)
reach[i][j] = graph[i][j];
/* Add all vertices one by one to the set of intermediate vertices.
---> Before start of a iteration, we have reachability values for all
pairs of vertices such that the reachability values consider only the
vertices in set {0, 1, 2, .. k-1} as intermediate vertices.
----> After the end of a iteration, vertex no. k is added to the set of
intermediate vertices and the set becomes {0, 1, 2, .. k} */
for (k = 0; k < V; k++)
{
// Pick all vertices as source one by one
for (i = 0; i < V; i++)
{
// Pick all vertices as destination for the
// above picked source
for (j = 0; j < V; j++)
{
// If vertex k is on a path from i to j,
// then make sure that the value of reach[i][j] is 1
reach[i][j] = reach[i][j] || (reach[i][k] && reach[k][j]);
}
}
}
// Print the shortest distance matrix
printSolution(reach);
}
First of all, could you explain me why the argument of the function is graph[][V] and not for example graph[V][V] ?
Then why do we initialize the matrix, that will finally have the shortest distances between every pair of vertices, with graph[V][V]?
And could you explain me what is done after the initialization, in the for-loops?
How could we write this command: reach[i][j] = reach[i][j] || (reach[i][k] && reach[k][j]);
elsewhise?
EDIT: graph is a boolean matrix, or not?
If so, then isn't reach also a boolean matrix?
So if we have this command: ( reach[i][j] = reach[i][j] || (reach[i][k] && reach[k][j]); ) and if reach[i][j]=1 then do we execute this: reach[i][j]=reach[i][j], elsewhise we check if (reach[i][k] + reach[k][j]) is non-zero?
Or have I understood it wrong?