2
$\begingroup$

I have a directed graph:

a = {{0, 1, 0, 0}, {0, 0, 1, 0}, {1, 0, 0, 1}, {1, 0, 0, 0}}; 
AdjacencyGraph[a]

I want to determine the cycle lengths in the directed graph. In the example above I would want Mathematica to return {3,4} because there is a cycle of length 3 and a cycle of length 4 in the directed graph.

$\endgroup$
0

1 Answer 1

3
$\begingroup$
a = {{0, 1, 0, 0}, {0, 0, 1, 0}, {1, 0, 0, 1}, {1, 0, 0, 0}};
g = AdjacencyGraph[a];

Length /@ FindCycle[g, Infinity, All]

{3, 4}

$\endgroup$
2
  • $\begingroup$ OK Thanks, but... I need to include cycles of length 2. For example: a = {{0, 1}, {1, 0}}; Map[Length, FindCycle[AdjacencyGraph[a], Infinity, All]] returns {}. Is there a way to convert the adjacency matrix into a list of edges and then use FindCycle? $\endgroup$
    – geoffrey
    Dec 4, 2023 at 17:02
  • 1
    $\begingroup$ @geoffrey I think you want to add the option DirectedEdges -> True, i.e., AdjacencyGraph[a, DirectedEdges -> True]. Then it should work. $\endgroup$
    – march
    Dec 4, 2023 at 22:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.