Floyd Warshall is O(n^3)
, and since O(n^3)
is a subset of O(n^4)
, it is also O(n^4)
.
Thus, by setting a new graph G'=(V,E',w')
where E' = V x V
(clique, complete graph) and w'(u,v) = 1 if (u,v) is in E, otherwise INFINITY
- by using Floyd-Warshall algorithm, each pair (u,v)
that ends up with a value less then infinity is in the closure.
A Theta(n^4) solution:
Q <- E (init) #(Q is a set)
for i from 1 to n:
for each v in V:
for each w in V:
for each u in V:
if (v,w) is in Q and (w,u) is in E:
Q <- Q U {(v,u)} #add (v,u) to Q
Complexity is trivially Theta(n^4)
, we only need to show it indeed finds the transitive closure.
By induction:
- For shortest path of length 1 from u to v it is the base clause, since (u,v) is in E.
- For each
k
:
Each pair(u,v)
with shortest path of lengthk>1
- there isw
such that there is a pathu -> ... -> w
, and an edge(w,v)
. From induction hypothesis, in previous iterations we added(u,w)
toQ
, and thus the condition will yield true, and we will add(u,v)
to the resulting setQ
.
Similary show that if some pair (u,v)
was added to Q, then there is a path u->..->w->v
, and thus it was rightfully added.
A second Theta(n^4)
solution:
Set G'
as described above, and for each vertex v
in V
run Bellman Ford from v
.
Each run of BF is Theta(n^3)
1, running it n
times is Theta(n^4)
(1) Technically it is O(VE)
, but for none sparse graphs E
is in Theta(V^2)