我发现了以下内容:
给定一个有向图,找出给定图中所有顶点对 (i, j) 的顶点 j 是否可以从另一个顶点 i 到达。
这里可达意味着有一条从顶点 i 到 j 的路径。
可达性矩阵称为图的传递闭包。
该图以邻接矩阵的形式给出,例如 'graph[V][V]' 其中如果从顶点 i 到顶点 j 有一条边,或者 i 等于 j,则 graph[i][j] 为 1,否则为图[i][j] 为 0。
我们可以使用 Floyd Warshall 计算距离矩阵 dist[V][V],如果 dist[i][j] 是无限的,则 j 不可从 i 到达,否则 j 可达且 dist[i][j] 的值将小于 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);
}
首先,你能解释一下为什么函数的参数是 graph[][V] 而不是 graph[V][V] 吗?
那我们为什么要初始化矩阵,它最终将在每对顶点之间具有最短距离,用graph[V][V]?
你能解释一下初始化后在for循环中做了什么吗?
我们怎么能写这个命令:reach[i][j] = reach[i][j] || (reach[i][k] && reach[k][j]);
elsewhise?
编辑:图是布尔矩阵,还是不是?
如果是这样,那么到达不是一个布尔矩阵吗?
所以如果我们有这个命令: (reach[i][j] = reach[i][j] || (reach[i][k] && reach[k][j]); ) 并且如果reach[i] [j]=1 然后我们执行这个:reach[i][j]=reach[i][j],否则我们检查 (reach[i][k] +reach[k][j]) 是否为非-零?
还是我理解错了?