在popoular实现中我们使用三个循环,循环变量说i,j,k。在这里我和我j用于表示两个顶点'来源&目的地分别如此' k'代表'中间体'顶点。如果我用循环变量放置循环' k' 3而不是放在第1我得到错误的答案。为什么呢?
答案 0 :(得分:4)
这是Floyd-Warshall算法背后的想法:
if:
i is connected to k and
k is connected to j
then if i and j are not connected,
create a connection between i and j
替代解释:
if:
i -> k and
k -> j
then if not i -> j
create i -> j
我想说的是,k将会处于逻辑连接的中间。中间顶点k负责给予N个邻居顶点直接连接的许可。
上述算法必须应用于| V |顶点,因此k上的循环必须是最外循环。
示例:
DiGraph:
Vertices: 0,1,2
Edges: (0,1), (1,2)
Representation: 0 -> 1 -> 2
算法:
k = 0
i = 0 ignore because k = i
i = 1 false because 1 -> 0 is wrong
i = 2 false because 2 -> 0 is wrong
k = 1
i = 0 true because 0 -> 1
j = 0 ignore because i = j
j = 1 ignore because j = k
j = 2 true because 1 -> 2
Since 0 -> 2 does not exist, create this edge
i = 1 ignore because i = k
i = 2 false because 2 -> 1 is wrong
k = 2
i = 0 true because we created this edge in the previous iteration
j = 0 ignore because i = j
j = 1 false because 2 -> 1 is wrong
j = 2 ignore because j = k
i = 1 true because 1 -> 2
j = 0 false because 2 -> 0 is wrong
j = 1 ignore because i = j
j = 2 ignore because j = k
i = 2 ignore because i = k
总而言之,
k需要执行| V |次
我需要执行| V |每个k的次数
j需要执行| V |每次成功的时间i - > ķ
时间复杂度:O(n 3 )
注意:如果您想应用算法或使用该算法以便更好地了解它的工作方式,请检查我的Github repo on the GraphADT,方法名称为transitiveClosure()
。该方法在Graph.java file。