Since you mention Floyd-Warshall, I think having an adjacency matrix is not a problem.
Let us look at it this way: a cycle of length 4 has the form a->b->c->d->a
.
Split that into two pairs of two edges: a->b->c
and c->d->a
.
Given the adjacency matrix, we can easily compute the matrix of shortest paths using exactly two edges: the shortest path from x
to z
is the minimum of x->y->z
for every vertex y
.
The vertex y
giving that minimum can be stored as well if we need to present the cycle, not only its length.
Now, to find the shortest cycle of length 4, just iterate over all possible pairs (a, c)
.
For each such pair, we have the minimum cost of traveling from a
to c
by exactly two edges and the minimum cost of traveling from c
to a
by exactly two edges.
The pair with the minimum sum of these two costs gives us the desired cycle.
The solution runs in O(n^3) with O(n^2) additional memory.