@@ -525,6 +525,29 @@ def test_components(self):
525525 v1 .connect (v3 )
526526 self .assertEqual (g .nc , 1 )
527527
528+ def test_iscyclic (self ):
529+
530+ # tree: acyclic
531+ g = UGraph ()
532+ v = [g .add_vertex (name = str (i )) for i in range (4 )]
533+ g .add_edge (v [0 ], v [1 ])
534+ g .add_edge (v [1 ], v [2 ])
535+ g .add_edge (v [2 ], v [3 ])
536+ self .assertFalse (g .iscyclic ())
537+
538+ # one extra edge closes a cycle
539+ g .add_edge (v [3 ], v [0 ])
540+ self .assertTrue (g .iscyclic ())
541+
542+ # two disconnected trees: still acyclic
543+ g2 = UGraph ()
544+ a = [g2 .add_vertex (name = f'a{ i } ' ) for i in range (3 )]
545+ b = [g2 .add_vertex (name = f'b{ i } ' ) for i in range (2 )]
546+ g2 .add_edge (a [0 ], a [1 ])
547+ g2 .add_edge (a [1 ], a [2 ])
548+ g2 .add_edge (b [0 ], b [1 ])
549+ self .assertFalse (g2 .iscyclic ())
550+
528551 def test_matrices (self ):
529552 g = UGraph ()
530553 # coordinates are needed so edge cost auto-computes, otherwise
@@ -796,6 +819,38 @@ def test_Dict(self):
796819 for v in g :
797820 self .assertIsInstance (v , DVertex )
798821
822+ def test_iscyclic (self ):
823+
824+ # diamond DAG: shared descendant, but acyclic -- a classic false
825+ # positive for a naive/buggy cycle detector
826+ g = DGraph ()
827+ v = [g .add_vertex (name = str (i )) for i in range (4 )]
828+ g .add_edge (v [0 ], v [1 ])
829+ g .add_edge (v [0 ], v [2 ])
830+ g .add_edge (v [1 ], v [3 ])
831+ g .add_edge (v [2 ], v [3 ])
832+ self .assertFalse (g .iscyclic ())
833+
834+ # a back-edge closes an actual directed cycle
835+ g .add_edge (v [3 ], v [0 ])
836+ self .assertTrue (g .iscyclic ())
837+
838+ # disconnected DAG components: still acyclic
839+ g2 = DGraph ()
840+ x = [g2 .add_vertex (name = f'x{ i } ' ) for i in range (2 )]
841+ y = [g2 .add_vertex (name = f'y{ i } ' ) for i in range (2 )]
842+ g2 .add_edge (x [0 ], x [1 ])
843+ g2 .add_edge (y [0 ], y [1 ])
844+ self .assertFalse (g2 .iscyclic ())
845+
846+ # pure 3-cycle, no self-loops
847+ g3 = DGraph ()
848+ t = [g3 .add_vertex (name = str (i )) for i in range (3 )]
849+ g3 .add_edge (t [0 ], t [1 ])
850+ g3 .add_edge (t [1 ], t [2 ])
851+ g3 .add_edge (t [2 ], t [0 ])
852+ self .assertTrue (g3 .iscyclic ())
853+
799854 def test_matrices (self ):
800855 # 3-4-5 triangle, directed 0->1, 0->2, 1->2 -- deliberately
801856 # asymmetric so directed-specific behaviour (out-degree only,
0 commit comments