Suppose I have an undirected graph which is stored as an adjacency matrix. The graph contains a single cycle; all other vertices are isolated.
How can I efficiently find the length of the cycle?
The best I've been able to come up with:
- Starting at row 0 of the matrix, traverse through rows until an initial
1
is found, say at rowstartVertex
and column k. Increment a counter. - Search column k for its other
1
, say at row j. Increment the counter. - Search row j for its other
1
value. Increment the counter. - Repeat steps 2 and 3 until a row or column which matches
startVertex
is found.
The complexity of this algorithm is $\mathcal{O}(V^2)$.
Is there a better algorithm out there?