Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tarjan_test.cc
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
33
38#include <algorithm>
39#include <utility>
40#include <vector>
41
42#include <gtest/gtest.h>
43#include <tpl_graph.H>
44#include <Tarjan.H>
45
46using namespace Aleph;
47
49
50// Helper functions
52{
53 return g.insert_node(value);
54}
55
57 int value = 0)
58{
59 return g.insert_arc(src, tgt, value);
60}
61
62// ============================================================================
63// Test: Empty graph
64// ============================================================================
65TEST(TarjanTest, EmptyGraph)
66{
69
70 // Test connected_components returning node lists
71 auto sccs = tarjan.connected_components(g);
72 EXPECT_TRUE(sccs.is_empty());
73
74 // Test connected_components with sizes
75 DynList<size_t> sizes;
76 tarjan.connected_components(g, sizes);
77 EXPECT_TRUE(sizes.is_empty());
78
79 // Test has_cycle
80 EXPECT_FALSE(tarjan.has_cycle(g));
81
82 // Test is_dag
83 EXPECT_TRUE(tarjan.is_dag(g));
84
85 // Test compute_cycle
86 Path<TestDigraph> path(g);
87 EXPECT_FALSE(tarjan.compute_cycle(g, path));
88 EXPECT_TRUE(path.is_empty());
89
90 // Test test_connectivity - empty graph is trivially connected
91 EXPECT_TRUE(tarjan.test_connectivity(g));
92}
93
94// ============================================================================
95// Test: Single node without self-loop
96// ============================================================================
97TEST(TarjanTest, SingleNodeNoLoop)
98{
100 auto n1 = add_node(g, 1);
101
103
104 // Test connected_components
105 auto sccs = tarjan.connected_components(g);
106 EXPECT_EQ(sccs.size(), 1u);
107 EXPECT_EQ(sccs.get_first().size(), 1u);
108 EXPECT_EQ(sccs.get_first().get_first(), n1);
109
110 // Test sizes
111 DynList<size_t> sizes;
112 tarjan.connected_components(g, sizes);
113 EXPECT_EQ(sizes.size(), 1u);
114 EXPECT_EQ(sizes.get_first(), 1u);
115
116 // Test has_cycle - single node without self-loop has no cycle
117 EXPECT_FALSE(tarjan.has_cycle(g));
118
119 // Test is_dag
120 EXPECT_TRUE(tarjan.is_dag(g));
121
122 // Test compute_cycle
123 Path<TestDigraph> path(g);
124 EXPECT_FALSE(tarjan.compute_cycle(g, path));
125
126 // Test connectivity
127 EXPECT_TRUE(tarjan.test_connectivity(g));
128}
129
130// ============================================================================
131// Test: Single node with self-loop
132// ============================================================================
133TEST(TarjanTest, SingleNodeWithLoop)
134{
135 TestDigraph g;
136 auto n1 = add_node(g, 1);
137 add_arc(g, n1, n1);
138
140
141 // Test connected_components
142 auto sccs = tarjan.connected_components(g);
143 EXPECT_EQ(sccs.size(), 1u);
144 EXPECT_EQ(sccs.get_first().size(), 1u);
145
146 // Test has_cycle - self-loop IS a cycle
147 EXPECT_TRUE(tarjan.has_cycle(g));
148
149 // Test is_dag
150 EXPECT_FALSE(tarjan.is_dag(g));
151
152 // Test compute_cycle - should find the self-loop cycle
153 Path<TestDigraph> path(g);
154 bool found = tarjan.compute_cycle(g, path);
155 EXPECT_TRUE(found);
156 EXPECT_FALSE(path.is_empty());
157 // For a self-loop, the path should start and end at the same node
158 EXPECT_EQ(path.get_first_node(), path.get_last_node());
159
160 // Test connectivity
161 EXPECT_TRUE(tarjan.test_connectivity(g));
162}
163
164// ============================================================================
165// Test: Two nodes, one arc (A -> B), no cycle
166// ============================================================================
167TEST(TarjanTest, TwoNodesNoCycle)
168{
169 TestDigraph g;
170 auto a = add_node(g, 1);
171 auto b = add_node(g, 2);
172 add_arc(g, a, b);
173
175
176 // Should have 2 SCCs (each node is its own SCC)
177 auto sccs = tarjan.connected_components(g);
178 EXPECT_EQ(sccs.size(), 2u);
179
180 // Test sizes
181 DynList<size_t> sizes;
182 tarjan.connected_components(g, sizes);
183 EXPECT_EQ(sizes.size(), 2u);
184 for (auto sz : sizes)
185 EXPECT_EQ(sz, 1u);
186
187 // No cycle
188 EXPECT_FALSE(tarjan.has_cycle(g));
189 EXPECT_TRUE(tarjan.is_dag(g));
190
191 Path<TestDigraph> path(g);
192 EXPECT_FALSE(tarjan.compute_cycle(g, path));
193
194 // Not strongly connected (can't go from B to A)
195 EXPECT_FALSE(tarjan.test_connectivity(g));
196}
197
198// ============================================================================
199// Test: Two nodes with cycle (A <-> B)
200// ============================================================================
201TEST(TarjanTest, TwoNodesWithCycle)
202{
203 TestDigraph g;
204 auto a = add_node(g, 1);
205 auto b = add_node(g, 2);
206 add_arc(g, a, b);
207 add_arc(g, b, a);
208
210
211 // Should have 1 SCC with both nodes
212 auto sccs = tarjan.connected_components(g);
213 EXPECT_EQ(sccs.size(), 1u);
214 EXPECT_EQ(sccs.get_first().size(), 2u);
215
216 // Has cycle
217 EXPECT_TRUE(tarjan.has_cycle(g));
218 EXPECT_FALSE(tarjan.is_dag(g));
219
220 // compute_cycle should find the cycle
221 Path<TestDigraph> path(g);
222 EXPECT_TRUE(tarjan.compute_cycle(g, path));
223 EXPECT_FALSE(path.is_empty());
224 EXPECT_EQ(path.get_first_node(), path.get_last_node());
225
226 // Strongly connected
227 EXPECT_TRUE(tarjan.test_connectivity(g));
228}
229
230// ============================================================================
231// Test: Linear chain (A -> B -> C -> D), DAG
232// ============================================================================
233TEST(TarjanTest, LinearChain)
234{
235 TestDigraph g;
236 auto a = add_node(g, 1);
237 auto b = add_node(g, 2);
238 auto c = add_node(g, 3);
239 auto d = add_node(g, 4);
240 add_arc(g, a, b);
241 add_arc(g, b, c);
242 add_arc(g, c, d);
243
245
246 // 4 SCCs
247 auto sccs = tarjan.connected_components(g);
248 EXPECT_EQ(sccs.size(), 4u);
249
250 EXPECT_FALSE(tarjan.has_cycle(g));
251 EXPECT_TRUE(tarjan.is_dag(g));
252 EXPECT_FALSE(tarjan.test_connectivity(g));
253}
254
255// ============================================================================
256// Test: Simple cycle (A -> B -> C -> A)
257// ============================================================================
258TEST(TarjanTest, SimpleCycle)
259{
260 TestDigraph g;
261 auto a = add_node(g, 1);
262 auto b = add_node(g, 2);
263 auto c = add_node(g, 3);
264 add_arc(g, a, b);
265 add_arc(g, b, c);
266 add_arc(g, c, a);
267
269
270 // 1 SCC with 3 nodes
271 auto sccs = tarjan.connected_components(g);
272 EXPECT_EQ(sccs.size(), 1u);
273 EXPECT_EQ(sccs.get_first().size(), 3u);
274
275 EXPECT_TRUE(tarjan.has_cycle(g));
276 EXPECT_FALSE(tarjan.is_dag(g));
277
278 Path<TestDigraph> path(g);
279 EXPECT_TRUE(tarjan.compute_cycle(g, path));
280 EXPECT_EQ(path.get_first_node(), path.get_last_node());
281
282 EXPECT_TRUE(tarjan.test_connectivity(g));
283}
284
285// ============================================================================
286// Test: Multiple SCCs
287// ============================================================================
288TEST(TarjanTest, MultipleSCCs)
289{
290 TestDigraph g;
291 auto a = add_node(g, 1);
292 auto b = add_node(g, 2);
293 auto c = add_node(g, 3);
294 auto d = add_node(g, 4);
295 auto e = add_node(g, 5);
296
297 // SCC1: A -> B -> C -> A
298 add_arc(g, a, b);
299 add_arc(g, b, c);
300 add_arc(g, c, a);
301
302 // SCC2: D -> E -> D
303 add_arc(g, d, e);
304 add_arc(g, e, d);
305
306 // Inter-SCC arc
307 add_arc(g, b, d);
308
310
311 // 2 SCCs
312 auto sccs = tarjan.connected_components(g);
313 EXPECT_EQ(sccs.size(), 2u);
314
315 // Check sizes (3 and 2)
316 DynList<size_t> sizes;
317 tarjan.connected_components(g, sizes);
318 EXPECT_EQ(sizes.size(), 2u);
319 size_t total = 0;
320 for (auto sz : sizes)
321 total += sz;
322 EXPECT_EQ(total, 5u);
323
324 // Has cycle
325 EXPECT_TRUE(tarjan.has_cycle(g));
326
327 // Not strongly connected (different SCCs)
328 EXPECT_FALSE(tarjan.test_connectivity(g));
329}
330
331// ============================================================================
332// Test: Connected components with block list and arc list
333// ============================================================================
334TEST(TarjanTest, ConnectedComponentsWithArcs)
335{
336 TestDigraph g;
337 auto a = add_node(g, 1);
338 auto b = add_node(g, 2);
339 auto c = add_node(g, 3);
340 auto d = add_node(g, 4);
341
342 // SCC1: A -> B -> A
343 add_arc(g, a, b);
344 add_arc(g, b, a);
345
346 // SCC2: C -> D -> C
347 add_arc(g, c, d);
348 add_arc(g, d, c);
349
350 // Inter-SCC arcs
351 auto cross1 = add_arc(g, b, c);
352 auto cross2 = add_arc(g, a, d);
353
355
356 DynList<TestDigraph> blk_list;
358 tarjan.connected_components(g, blk_list, arc_list);
359
360 // 2 blocks
361 EXPECT_EQ(blk_list.size(), 2u);
362
363 // 2 inter-block arcs
364 EXPECT_EQ(arc_list.size(), 2u);
365
366 // Verify the cross arcs are in the list
367 bool found_cross1 = false, found_cross2 = false;
368 for (auto arc : arc_list)
369 {
370 if (arc == cross1)
371 found_cross1 = true;
372 if (arc == cross2)
373 found_cross2 = true;
374 }
375 EXPECT_TRUE(found_cross1);
376 EXPECT_TRUE(found_cross2);
377}
378
379// ============================================================================
380// Test: compute_cycle from specific source node
381// ============================================================================
382TEST(TarjanTest, ComputeCycleFromSource)
383{
384 TestDigraph g;
385 auto a = add_node(g, 1);
386 auto b = add_node(g, 2);
387 auto c = add_node(g, 3);
388 add_arc(g, a, b);
389 add_arc(g, b, c);
390 add_arc(g, c, b); // cycle between B and C only
391
393
394 // Starting from A, we should find the cycle in B-C
395 Path<TestDigraph> path1(g);
396 bool found1 = tarjan.compute_cycle(g, a, path1);
397 EXPECT_TRUE(found1);
398
399 // Starting from B, we should find the cycle
400 Path<TestDigraph> path2(g);
401 bool found2 = tarjan.compute_cycle(g, b, path2);
402 EXPECT_TRUE(found2);
403}
404
405// ============================================================================
406// Test: Compute_Cycle_In_Digraph wrapper class
407// ============================================================================
408TEST(TarjanTest, ComputeCycleInTestDigraphClass)
409{
410 TestDigraph g;
411 auto a = add_node(g, 1);
412 auto b = add_node(g, 2);
413 auto c = add_node(g, 3);
414 add_arc(g, a, b);
415 add_arc(g, b, c);
416 add_arc(g, c, a);
417
418 // Test with operator()(g, path)
420 Path<TestDigraph> path(g);
421 bool found = finder(g, path);
422 EXPECT_TRUE(found);
423 EXPECT_FALSE(path.is_empty());
424
425 // Test with operator()(g) returning path
426 auto path2 = finder(g);
427 EXPECT_FALSE(path2.is_empty());
428
429 // Test with operator()(g, src) returning path
430 auto path3 = finder(g, a);
431 EXPECT_FALSE(path3.is_empty());
432}
433
434// ============================================================================
435// Test: DAG with diamond shape
436// ============================================================================
437TEST(TarjanTest, DiamondDAG)
438{
439 TestDigraph g;
440 auto a = add_node(g, 1);
441 auto b = add_node(g, 2);
442 auto c = add_node(g, 3);
443 auto d = add_node(g, 4);
444 add_arc(g, a, b);
445 add_arc(g, a, c);
446 add_arc(g, b, d);
447 add_arc(g, c, d);
448
450
451 // 4 SCCs (each node is its own SCC)
452 auto sccs = tarjan.connected_components(g);
453 EXPECT_EQ(sccs.size(), 4u);
454
455 EXPECT_FALSE(tarjan.has_cycle(g));
456 EXPECT_TRUE(tarjan.is_dag(g));
457 EXPECT_FALSE(tarjan.test_connectivity(g));
458}
459
460// ============================================================================
461// Test: Complex graph with nested cycles
462// ============================================================================
463TEST(TarjanTest, ComplexNestedCycles)
464{
465 TestDigraph g;
466 auto n1 = add_node(g, 1);
467 auto n2 = add_node(g, 2);
468 auto n3 = add_node(g, 3);
469 auto n4 = add_node(g, 4);
470 auto n5 = add_node(g, 5);
471 auto n6 = add_node(g, 6);
472
473 // Create a strongly connected component with all 6 nodes
474 add_arc(g, n1, n2);
475 add_arc(g, n2, n3);
476 add_arc(g, n3, n1); // small cycle
477 add_arc(g, n3, n4);
478 add_arc(g, n4, n5);
479 add_arc(g, n5, n6);
480 add_arc(g, n6, n1); // large cycle back to n1
481
483
484 // All nodes should be in one SCC
485 auto sccs = tarjan.connected_components(g);
486 EXPECT_EQ(sccs.size(), 1u);
487 EXPECT_EQ(sccs.get_first().size(), 6u);
488
489 EXPECT_TRUE(tarjan.has_cycle(g));
490 EXPECT_TRUE(tarjan.test_connectivity(g));
491
492 Path<TestDigraph> path(g);
493 EXPECT_TRUE(tarjan.compute_cycle(g, path));
494 EXPECT_EQ(path.get_first_node(), path.get_last_node());
495}
496
497// ============================================================================
498// Test: Operator() overloads for DynDlist
499// ============================================================================
500TEST(TarjanTest, DynDlistOverloads)
501{
502 TestDigraph g;
503 auto a = add_node(g, 1);
504 auto b = add_node(g, 2);
505 add_arc(g, a, b);
506 add_arc(g, b, a);
507
509
510 // Test DynDlist<GT> overload
511 DynDlist<TestDigraph> blk_list;
513 tarjan(g, blk_list, arc_list);
514 EXPECT_EQ(blk_list.size(), 1u);
515 EXPECT_TRUE(arc_list.is_empty()); // no inter-block arcs
516
517 // Test DynDlist<DynDlist<Node*>> overload
519 tarjan(g, blks);
520 EXPECT_EQ(blks.size(), 1u);
521 EXPECT_EQ(blks.get_first().size(), 2u);
522}
523
524// ============================================================================
525// Test: Disconnected graph components (no edges between them)
526// ============================================================================
527TEST(TarjanTest, DisconnectedComponents)
528{
529 TestDigraph g;
530 // Component 1: A -> B -> C -> A
531 auto a = add_node(g, 1);
532 auto b = add_node(g, 2);
533 auto c = add_node(g, 3);
534 add_arc(g, a, b);
535 add_arc(g, b, c);
536 add_arc(g, c, a);
537
538 // Component 2: D (isolated)
539 auto d = add_node(g, 4);
540 (void)d;
541
542 // Component 3: E -> F
543 auto e = add_node(g, 5);
544 auto f = add_node(g, 6);
545 add_arc(g, e, f);
546
548
549 // Should have 4 SCCs: {A,B,C}, {D}, {E}, {F}
550 auto sccs = tarjan.connected_components(g);
551 EXPECT_EQ(sccs.size(), 4u);
552
553 // Check sizes
554 DynList<size_t> sizes;
555 tarjan.connected_components(g, sizes);
556 EXPECT_EQ(sizes.size(), 4u);
557
558 // One SCC has size 3, others have size 1
559 size_t count_3 = 0, count_1 = 0;
560 for (auto sz : sizes)
561 {
562 if (sz == 3)
563 count_3++;
564 else if (sz == 1)
565 count_1++;
566 }
567 EXPECT_EQ(count_3, 1u);
568 EXPECT_EQ(count_1, 3u);
569
570 // Has cycle (in A-B-C)
571 EXPECT_TRUE(tarjan.has_cycle(g));
572
573 // Not strongly connected
574 EXPECT_FALSE(tarjan.test_connectivity(g));
575}
576
577// ============================================================================
578// Test: Large cycle
579// ============================================================================
580TEST(TarjanTest, LargeCycle)
581{
582 TestDigraph g;
583 const size_t N = 100;
584
586 for (size_t i = 0; i < N; ++i)
587 nodes.append(add_node(g, static_cast<int>(i)));
588
589 // Create a cycle: 0 -> 1 -> 2 -> ... -> 99 -> 0
590 auto it = nodes.get_it();
591 auto prev = it.get_curr();
592 auto first = prev;
593 for (it.next(); it.has_curr(); it.next())
594 {
595 auto curr = it.get_curr();
596 add_arc(g, prev, curr);
597 prev = curr;
598 }
599 add_arc(g, prev, first); // close the cycle
600
602
603 // One SCC with all N nodes
604 auto sccs = tarjan.connected_components(g);
605 EXPECT_EQ(sccs.size(), 1u);
606 EXPECT_EQ(sccs.get_first().size(), N);
607
608 EXPECT_TRUE(tarjan.has_cycle(g));
609 EXPECT_TRUE(tarjan.test_connectivity(g));
610
611 Path<TestDigraph> path(g);
612 EXPECT_TRUE(tarjan.compute_cycle(g, path));
613}
614
615// ============================================================================
616// Test: Graph with only inter-SCC arcs (tree-like structure of SCCs)
617// ============================================================================
618TEST(TarjanTest, SCCTree)
619{
620 TestDigraph g;
621 // SCC A: a1 -> a2 -> a1
622 auto a1 = add_node(g, 1);
623 auto a2 = add_node(g, 2);
624 add_arc(g, a1, a2);
625 add_arc(g, a2, a1);
626
627 // SCC B: b1 -> b2 -> b1
628 auto b1 = add_node(g, 3);
629 auto b2 = add_node(g, 4);
630 add_arc(g, b1, b2);
631 add_arc(g, b2, b1);
632
633 // SCC C: c1 -> c2 -> c1
634 auto c1 = add_node(g, 5);
635 auto c2 = add_node(g, 6);
636 add_arc(g, c1, c2);
637 add_arc(g, c2, c1);
638
639 // Tree structure: A -> B, A -> C
640 add_arc(g, a1, b1);
641 add_arc(g, a2, c1);
642
644
645 // 3 SCCs
646 auto sccs = tarjan.connected_components(g);
647 EXPECT_EQ(sccs.size(), 3u);
648
649 // Each SCC has 2 nodes
650 for (auto &scc : sccs)
651 EXPECT_EQ(scc.size(), 2u);
652
653 // Has cycle (within each SCC)
654 EXPECT_TRUE(tarjan.has_cycle(g));
655
656 // Not strongly connected
657 EXPECT_FALSE(tarjan.test_connectivity(g));
658}
659
660// ============================================================================
661// Test: num_connected_components convenience method
662// ============================================================================
663TEST(TarjanTest, NumConnectedComponents)
664{
665 TestDigraph g;
666
667 // Empty graph
669 EXPECT_EQ(tarjan1.num_connected_components(g), 0u);
670
671 // Single node
672 auto a = add_node(g, 1);
674 EXPECT_EQ(tarjan2.num_connected_components(g), 1u);
675
676 // Two nodes, no connection = 2 SCCs
677 auto b = add_node(g, 2);
679 EXPECT_EQ(tarjan3.num_connected_components(g), 2u);
680
681 // Add bidirectional connection = 1 SCC
682 add_arc(g, a, b);
683 add_arc(g, b, a);
685 EXPECT_EQ(tarjan4.num_connected_components(g), 1u);
686}
687
688// ============================================================================
689// Test: Null source node validation
690// ============================================================================
691TEST(TarjanTest, NullSourceValidation)
692{
693 TestDigraph g;
694 add_node(g, 1);
695
697 Path<TestDigraph> path(g);
698
699 EXPECT_THROW((void) tarjan.compute_cycle(g, nullptr, path), std::domain_error);
700}
701
702// ============================================================================
703// Test: Filter accessor
704// ============================================================================
705TEST(TarjanTest, FilterAccessor)
706{
708
709 // Just verify the methods compile and return references
710 [[maybe_unused]] auto &filter = tarjan.get_filter();
711
712 const Tarjan_Connected_Components<TestDigraph> &const_tarjan = tarjan;
713 [[maybe_unused]] const auto &const_filter = const_tarjan.get_filter();
714}
715
716// ============================================================================
717// Test: State getters
718// ============================================================================
719TEST(TarjanTest, StateGetters)
720{
721 TestDigraph g;
722 auto a = add_node(g, 1);
723 auto b = add_node(g, 2);
724 add_arc(g, a, b);
725 add_arc(g, b, a);
726
728
729 // Before computation
730 EXPECT_FALSE(tarjan.has_computation());
731 EXPECT_EQ(tarjan.get_graph(), nullptr);
732
733 // After computation
734 auto sccs = tarjan.connected_components(g);
735 EXPECT_TRUE(tarjan.has_computation());
736 EXPECT_EQ(tarjan.get_graph(), &g);
737}
738
739// ============================================================================
740// Test: Move semantics
741// ============================================================================
742TEST(TarjanTest, MoveSemantics)
743{
744 TestDigraph g;
745 auto a = add_node(g, 1);
746 auto b = add_node(g, 2);
747 add_arc(g, a, b);
748 add_arc(g, b, a);
749
751 auto sccs1 = tarjan1.connected_components(g);
752 EXPECT_EQ(sccs1.size(), 1u);
753
754 // Move constructor
755 Tarjan_Connected_Components<TestDigraph> tarjan2(std::move(tarjan1));
756 auto sccs2 = tarjan2.connected_components(g);
757 EXPECT_EQ(sccs2.size(), 1u);
758
759 // Move assignment
761 tarjan3 = std::move(tarjan2);
762 auto sccs3 = tarjan3.connected_components(g);
763 EXPECT_EQ(sccs3.size(), 1u);
764}
765
766// ============================================================================
767// Test: Custom arc filter
768// ============================================================================
770{
771 bool operator()(TestDigraph::Arc *a) const noexcept
772 {
773 return a->get_info() != 0;
774 }
775};
776
777TEST(TarjanTest, CustomArcFilter)
778{
779 TestDigraph g;
780 auto a = add_node(g, 1);
781 auto b = add_node(g, 2);
782 auto c = add_node(g, 3);
783
784 // Create cycle a -> b -> c -> a, but with weight 0 on c -> a
785 add_arc(g, a, b, 1);
786 add_arc(g, b, c, 1);
787 add_arc(g, c, a, 0); // This arc will be filtered out
788
789 // Without filter: 1 SCC
791 EXPECT_EQ(tarjan1.num_connected_components(g), 1u);
792
793 // With filter: 3 SCCs (c -> a is filtered, breaking the cycle)
795 EXPECT_EQ(tarjan2.num_connected_components(g), 3u);
796}
797
798// ============================================================================
799// Test: Stress test with large graph
800// ============================================================================
801TEST(TarjanTest, LargeGraphStress)
802{
803 TestDigraph g;
804 const size_t N = 1000;
805
806 // Create N nodes
807 std::vector<TestDigraph::Node*> nodes(N);
808 for (size_t i = 0; i < N; ++i)
809 nodes[i] = add_node(g, static_cast<int>(i));
810
811 // Create a single large cycle
812 for (size_t i = 0; i < N; ++i)
813 add_arc(g, nodes[i], nodes[(i + 1) % N]);
814
816
817 // Should be 1 SCC
818 EXPECT_EQ(tarjan.num_connected_components(g), 1u);
819
820 // Should be strongly connected
821 EXPECT_TRUE(tarjan.test_connectivity(g));
822
823 // Should have a cycle
824 EXPECT_TRUE(tarjan.has_cycle(g));
825}
826
827// ============================================================================
828// Test: Multiple disjoint cycles
829// ============================================================================
830TEST(TarjanTest, MultipleDisjointCycles)
831{
832 TestDigraph g;
833 const size_t NUM_CYCLES = 10;
834 const size_t CYCLE_SIZE = 5;
835
836 std::vector<TestDigraph::Node*> first_nodes;
837
838 for (size_t c = 0; c < NUM_CYCLES; ++c)
839 {
840 std::vector<TestDigraph::Node*> cycle_nodes(CYCLE_SIZE);
841 for (size_t i = 0; i < CYCLE_SIZE; ++i)
842 cycle_nodes[i] = add_node(g, static_cast<int>(c * CYCLE_SIZE + i));
843
844 first_nodes.push_back(cycle_nodes[0]);
845
846 for (size_t i = 0; i < CYCLE_SIZE; ++i)
847 add_arc(g, cycle_nodes[i], cycle_nodes[(i + 1) % CYCLE_SIZE]);
848 }
849
851
852 // Should have NUM_CYCLES SCCs
853 EXPECT_EQ(tarjan.num_connected_components(g), NUM_CYCLES);
854
855 // Should have cycles
856 EXPECT_TRUE(tarjan.has_cycle(g));
857
858 // Verify each cycle is an SCC
859 DynList<size_t> sizes;
860 tarjan.connected_components(g, sizes);
861 for (auto sz : sizes)
862 EXPECT_EQ(sz, CYCLE_SIZE);
863}
864
865// ============================================================================
866// Test: Path cycle verification
867// ============================================================================
868TEST(TarjanTest, CyclePathVerification)
869{
870 TestDigraph g;
871 auto a = add_node(g, 1);
872 auto b = add_node(g, 2);
873 auto c = add_node(g, 3);
874 add_arc(g, a, b);
875 add_arc(g, b, c);
876 add_arc(g, c, a);
877
879 Path<TestDigraph> path(g);
880 bool found = tarjan.compute_cycle(g, path);
881
882 ASSERT_TRUE(found);
883 ASSERT_FALSE(path.is_empty());
884
885 // Verify cycle property: first node == last node
886 EXPECT_EQ(path.get_first_node(), path.get_last_node());
887
888 // Verify all nodes in path are connected
889 size_t path_len = 0;
890 for (Path<TestDigraph>::Iterator it(path); it.has_curr(); it.next())
891 ++path_len;
892
893 // Path should have at least 2 nodes for a valid cycle (start + end being same)
894 EXPECT_GE(path_len, 2u);
895}
896
897// ============================================================================
898// Test: Complete digraph (all nodes connected to all others)
899// ============================================================================
900TEST(TarjanTest, CompleteDigraph)
901{
902 TestDigraph g;
903 const size_t N = 10;
904
905 std::vector<TestDigraph::Node*> nodes(N);
906 for (size_t i = 0; i < N; ++i)
907 nodes[i] = add_node(g, static_cast<int>(i));
908
909 // Create complete digraph
910 for (size_t i = 0; i < N; ++i)
911 for (size_t j = 0; j < N; ++j)
912 if (i != j)
913 add_arc(g, nodes[i], nodes[j]);
914
916
917 // All nodes in one SCC
918 EXPECT_EQ(tarjan.num_connected_components(g), 1u);
919 EXPECT_TRUE(tarjan.test_connectivity(g));
920 EXPECT_TRUE(tarjan.has_cycle(g));
921}
922
923// ============================================================================
924// Test: Reusing Tarjan instance for multiple graphs
925// ============================================================================
926TEST(TarjanTest, ReuseInstance)
927{
929
930 // Graph 1: simple cycle
931 TestDigraph g1;
932 auto a1 = add_node(g1, 1);
933 auto b1 = add_node(g1, 2);
934 add_arc(g1, a1, b1);
935 add_arc(g1, b1, a1);
936
937 EXPECT_EQ(tarjan.num_connected_components(g1), 1u);
938 EXPECT_TRUE(tarjan.has_cycle(g1));
939
940 // Graph 2: DAG
941 TestDigraph g2;
942 auto a2 = add_node(g2, 1);
943 auto b2 = add_node(g2, 2);
944 auto c2 = add_node(g2, 3);
945 add_arc(g2, a2, b2);
946 add_arc(g2, b2, c2);
947
948 EXPECT_EQ(tarjan.num_connected_components(g2), 3u);
949 EXPECT_FALSE(tarjan.has_cycle(g2));
950 EXPECT_TRUE(tarjan.is_dag(g2));
951}
952
953// ============================================================================
954// Test: the blocks go after those that the lists hold, which do not change
955// ============================================================================
956TEST(TarjanTest, ListsThatHoldBlocksKeepThem)
957{
961 {
962 TestDigraph gone; // its block stays in the list after it goes
963 auto a = add_node(gone, 1);
964 auto b = add_node(gone, 2);
965 add_arc(gone, a, b);
966 add_arc(gone, b, a);
967 tarjan.connected_components(gone, blocks, arcs);
968 }
969 ASSERT_EQ(blocks.size(), 1u);
970 ASSERT_TRUE(arcs.is_empty());
971
972 TestDigraph g;
973 auto c = add_node(g, 3);
974 auto d = add_node(g, 4);
975 auto e = add_node(g, 5);
976 add_arc(g, c, d);
977 add_arc(g, d, c);
978 auto between = add_arc(g, d, e);
979 tarjan.connected_components(g, blocks, arcs); // g twice, into the same lists
980 tarjan.connected_components(g, blocks, arcs);
981
982 // the block of the graph that went, and twice the two of g: each with
983 // its own arcs alone, toward its own nodes
984 ASSERT_EQ(blocks.size(), 5u);
985 std::vector<std::pair<size_t, size_t>> sizes;
986 for (auto & blk : blocks)
987 {
988 sizes.emplace_back(blk.get_num_nodes(), blk.get_num_arcs());
989 std::vector<TestDigraph::Node *> nodes;
990 for (auto it = blk.get_node_it(); it.has_curr(); it.next_ne())
991 nodes.push_back(it.get_curr());
992 auto mine = [&nodes] (TestDigraph::Node * p)
993 {
994 return std::find(nodes.begin(), nodes.end(), p) != nodes.end();
995 };
996 for (auto it = blk.get_arc_it(); it.has_curr(); it.next_ne())
997 {
998 EXPECT_TRUE(mine(blk.get_src_node(it.get_curr())));
999 EXPECT_TRUE(mine(blk.get_tgt_node(it.get_curr())));
1000 }
1001 }
1002 const std::vector<std::pair<size_t, size_t>> expected =
1003 { {2, 2}, {1, 0}, {2, 2}, {1, 0}, {2, 2} };
1004 std::sort(sizes.begin(), sizes.end());
1005 auto sorted = expected;
1006 std::sort(sorted.begin(), sorted.end());
1007 EXPECT_EQ(sizes, sorted);
1008 ASSERT_EQ(blocks.get_first().get_num_nodes(), 2u); // that of the graph that went
1009 EXPECT_EQ(blocks.get_first().get_num_arcs(), 2u);
1010
1011 // the arc between the blocks of g, once for each time
1012 ASSERT_EQ(arcs.size(), 2u);
1013 EXPECT_TRUE(arcs.all([between] (TestDigraph::Arc * a) { return a == between; }));
1014}
1015
1016// ============================================================================
1017// EXTENDED EXHAUSTIVE TESTS
1018// ============================================================================
1019
1020// ============================================================================
1021// Test: Star graph (hub with many spokes) - outward
1022// ============================================================================
1023TEST(TarjanExtended, StarGraphOutward)
1024{
1025 TestDigraph g;
1026 const size_t N = 50;
1027
1028 auto hub = add_node(g, 0);
1029 for (size_t i = 1; i <= N; ++i)
1030 {
1031 auto spoke = add_node(g, static_cast<int>(i));
1032 add_arc(g, hub, spoke); // hub -> spoke
1033 }
1034
1036
1037 // N+1 SCCs (each node is its own SCC)
1038 EXPECT_EQ(tarjan.num_connected_components(g), N + 1);
1039 EXPECT_FALSE(tarjan.has_cycle(g));
1040 EXPECT_TRUE(tarjan.is_dag(g));
1041 EXPECT_FALSE(tarjan.test_connectivity(g));
1042}
1043
1044// ============================================================================
1045// Test: Star graph (hub with many spokes) - inward
1046// ============================================================================
1047TEST(TarjanExtended, StarGraphInward)
1048{
1049 TestDigraph g;
1050 const size_t N = 50;
1051
1052 auto hub = add_node(g, 0);
1053 for (size_t i = 1; i <= N; ++i)
1054 {
1055 auto spoke = add_node(g, static_cast<int>(i));
1056 add_arc(g, spoke, hub); // spoke -> hub
1057 }
1058
1060
1061 EXPECT_EQ(tarjan.num_connected_components(g), N + 1);
1062 EXPECT_FALSE(tarjan.has_cycle(g));
1063 EXPECT_TRUE(tarjan.is_dag(g));
1064}
1065
1066// ============================================================================
1067// Test: Wheel graph (cycle with hub connected to all)
1068// ============================================================================
1069TEST(TarjanExtended, WheelGraph)
1070{
1071 TestDigraph g;
1072 const size_t N = 20;
1073
1074 auto hub = add_node(g, 0);
1075 std::vector<TestDigraph::Node *> rim(N);
1076
1077 for (size_t i = 0; i < N; ++i)
1078 {
1079 rim[i] = add_node(g, static_cast<int>(i + 1));
1080 add_arc(g, hub, rim[i]); // hub -> rim
1081 add_arc(g, rim[i], hub); // rim -> hub (bidirectional)
1082 }
1083
1084 // Create rim cycle
1085 for (size_t i = 0; i < N; ++i)
1086 add_arc(g, rim[i], rim[(i + 1) % N]);
1087
1089
1090 // All nodes should be in one SCC
1091 EXPECT_EQ(tarjan.num_connected_components(g), 1u);
1092 EXPECT_TRUE(tarjan.has_cycle(g));
1093 EXPECT_TRUE(tarjan.test_connectivity(g));
1094}
1095
1096// ============================================================================
1097// Test: Binary tree DAG
1098// ============================================================================
1099TEST(TarjanExtended, BinaryTreeDAG)
1100{
1101 TestDigraph g;
1102 const size_t DEPTH = 6; // 2^6 - 1 = 63 nodes
1103
1104 std::vector<TestDigraph::Node *> nodes;
1105 nodes.push_back(add_node(g, 0)); // root
1106
1107 for (size_t level = 0; level < DEPTH - 1; ++level)
1108 {
1109 size_t start = (1 << level) - 1;
1110 size_t end = (1 << (level + 1)) - 1;
1111
1112 for (size_t i = start; i < end && i < nodes.size(); ++i)
1113 {
1114 auto left = add_node(g, static_cast<int>(nodes.size()));
1115 nodes.push_back(left);
1116 add_arc(g, nodes[i], left);
1117
1118 auto right = add_node(g, static_cast<int>(nodes.size()));
1119 nodes.push_back(right);
1120 add_arc(g, nodes[i], right);
1121 }
1122 }
1123
1125
1126 // Each node is its own SCC (DAG)
1127 EXPECT_EQ(tarjan.num_connected_components(g), nodes.size());
1128 EXPECT_FALSE(tarjan.has_cycle(g));
1129 EXPECT_TRUE(tarjan.is_dag(g));
1130}
1131
1132// ============================================================================
1133// Test: Multiple self-loops
1134// ============================================================================
1135TEST(TarjanExtended, MultipleSelfLoops)
1136{
1137 TestDigraph g;
1138 const size_t N = 20;
1139
1140 for (size_t i = 0; i < N; ++i)
1141 {
1142 auto n = add_node(g, static_cast<int>(i));
1143 add_arc(g, n, n); // self-loop
1144 }
1145
1147
1148 // Each node is its own SCC (but each has a cycle)
1149 EXPECT_EQ(tarjan.num_connected_components(g), N);
1150 EXPECT_TRUE(tarjan.has_cycle(g));
1151 EXPECT_FALSE(tarjan.is_dag(g));
1152 EXPECT_FALSE(tarjan.test_connectivity(g));
1153}
1154
1155// ============================================================================
1156// Test: Chain of SCCs
1157// ============================================================================
1158TEST(TarjanExtended, ChainOfSCCs)
1159{
1160 TestDigraph g;
1161 const size_t NUM_SCCS = 10;
1162 const size_t SCC_SIZE = 3;
1163
1164 std::vector<TestDigraph::Node *> first_of_scc;
1165
1166 for (size_t s = 0; s < NUM_SCCS; ++s)
1167 {
1168 std::vector<TestDigraph::Node *> scc_nodes(SCC_SIZE);
1169 for (size_t i = 0; i < SCC_SIZE; ++i)
1170 scc_nodes[i] = add_node(g, static_cast<int>(s * SCC_SIZE + i));
1171
1172 first_of_scc.push_back(scc_nodes[0]);
1173
1174 // Create cycle within SCC
1175 for (size_t i = 0; i < SCC_SIZE; ++i)
1176 add_arc(g, scc_nodes[i], scc_nodes[(i + 1) % SCC_SIZE]);
1177
1178 // Connect to previous SCC
1179 if (s > 0)
1180 add_arc(g, first_of_scc[s - 1], scc_nodes[0]);
1181 }
1182
1184
1185 EXPECT_EQ(tarjan.num_connected_components(g), NUM_SCCS);
1186 EXPECT_TRUE(tarjan.has_cycle(g));
1187 EXPECT_FALSE(tarjan.test_connectivity(g));
1188
1189 DynList<size_t> sizes;
1190 tarjan.connected_components(g, sizes);
1191 for (auto sz : sizes)
1192 EXPECT_EQ(sz, SCC_SIZE);
1193}
1194
1195// ============================================================================
1196// Test: Diamond pattern SCCs
1197// ============================================================================
1198TEST(TarjanExtended, DiamondPatternSCCs)
1199{
1200 TestDigraph g;
1201
1202 // Top SCC
1203 auto t1 = add_node(g, 1);
1204 auto t2 = add_node(g, 2);
1205 add_arc(g, t1, t2);
1206 add_arc(g, t2, t1);
1207
1208 // Left SCC
1209 auto l1 = add_node(g, 3);
1210 auto l2 = add_node(g, 4);
1211 add_arc(g, l1, l2);
1212 add_arc(g, l2, l1);
1213
1214 // Right SCC
1215 auto r1 = add_node(g, 5);
1216 auto r2 = add_node(g, 6);
1217 add_arc(g, r1, r2);
1218 add_arc(g, r2, r1);
1219
1220 // Bottom SCC
1221 auto b1 = add_node(g, 7);
1222 auto b2 = add_node(g, 8);
1223 add_arc(g, b1, b2);
1224 add_arc(g, b2, b1);
1225
1226 // Connect in diamond pattern
1227 add_arc(g, t1, l1);
1228 add_arc(g, t2, r1);
1229 add_arc(g, l2, b1);
1230 add_arc(g, r2, b2);
1231
1233
1234 EXPECT_EQ(tarjan.num_connected_components(g), 4u);
1235 EXPECT_TRUE(tarjan.has_cycle(g));
1236 EXPECT_FALSE(tarjan.test_connectivity(g));
1237}
1238
1239// ============================================================================
1240// Test: Bipartite-like structure (no cycles)
1241// ============================================================================
1242TEST(TarjanExtended, BipartiteDAG)
1243{
1244 TestDigraph g;
1245 const size_t LEFT_SIZE = 10;
1246 const size_t RIGHT_SIZE = 10;
1247
1248 std::vector<TestDigraph::Node *> left(LEFT_SIZE);
1249 std::vector<TestDigraph::Node *> right(RIGHT_SIZE);
1250
1251 for (size_t i = 0; i < LEFT_SIZE; ++i)
1252 left[i] = add_node(g, static_cast<int>(i));
1253
1254 for (size_t i = 0; i < RIGHT_SIZE; ++i)
1255 right[i] = add_node(g, static_cast<int>(LEFT_SIZE + i));
1256
1257 // All left -> all right
1258 for (size_t i = 0; i < LEFT_SIZE; ++i)
1259 for (size_t j = 0; j < RIGHT_SIZE; ++j)
1260 add_arc(g, left[i], right[j]);
1261
1263
1264 EXPECT_EQ(tarjan.num_connected_components(g), LEFT_SIZE + RIGHT_SIZE);
1265 EXPECT_FALSE(tarjan.has_cycle(g));
1266 EXPECT_TRUE(tarjan.is_dag(g));
1267}
1268
1269// ============================================================================
1270// Test: Strongly connected bipartite (all edges both ways)
1271// ============================================================================
1272TEST(TarjanExtended, StronglyConnectedBipartite)
1273{
1274 TestDigraph g;
1275 const size_t LEFT_SIZE = 5;
1276 const size_t RIGHT_SIZE = 5;
1277
1278 std::vector<TestDigraph::Node *> left(LEFT_SIZE);
1279 std::vector<TestDigraph::Node *> right(RIGHT_SIZE);
1280
1281 for (size_t i = 0; i < LEFT_SIZE; ++i)
1282 left[i] = add_node(g, static_cast<int>(i));
1283
1284 for (size_t i = 0; i < RIGHT_SIZE; ++i)
1285 right[i] = add_node(g, static_cast<int>(LEFT_SIZE + i));
1286
1287 // All left <-> all right (bidirectional)
1288 for (size_t i = 0; i < LEFT_SIZE; ++i)
1289 for (size_t j = 0; j < RIGHT_SIZE; ++j)
1290 {
1291 add_arc(g, left[i], right[j]);
1292 add_arc(g, right[j], left[i]);
1293 }
1294
1296
1297 EXPECT_EQ(tarjan.num_connected_components(g), 1u);
1298 EXPECT_TRUE(tarjan.has_cycle(g));
1299 EXPECT_TRUE(tarjan.test_connectivity(g));
1300}
1301
1302// ============================================================================
1303// Test: Grid graph (no cycles, DAG)
1304// ============================================================================
1305TEST(TarjanExtended, GridDAG)
1306{
1307 TestDigraph g;
1308 const size_t ROWS = 5;
1309 const size_t COLS = 5;
1310
1311 std::vector<std::vector<TestDigraph::Node *>> grid(ROWS,
1312 std::vector<TestDigraph::Node *>(COLS));
1313
1314 for (size_t r = 0; r < ROWS; ++r)
1315 for (size_t c = 0; c < COLS; ++c)
1316 grid[r][c] = add_node(g, static_cast<int>(r * COLS + c));
1317
1318 // Connect right and down only (DAG)
1319 for (size_t r = 0; r < ROWS; ++r)
1320 for (size_t c = 0; c < COLS; ++c)
1321 {
1322 if (c + 1 < COLS)
1323 add_arc(g, grid[r][c], grid[r][c + 1]);
1324 if (r + 1 < ROWS)
1325 add_arc(g, grid[r][c], grid[r + 1][c]);
1326 }
1327
1329
1330 EXPECT_EQ(tarjan.num_connected_components(g), ROWS * COLS);
1331 EXPECT_FALSE(tarjan.has_cycle(g));
1332 EXPECT_TRUE(tarjan.is_dag(g));
1333}
1334
1335// ============================================================================
1336// Test: Grid graph with back edges (cycles)
1337// ============================================================================
1338TEST(TarjanExtended, GridWithCycles)
1339{
1340 TestDigraph g;
1341 const size_t ROWS = 4;
1342 const size_t COLS = 4;
1343
1344 std::vector<std::vector<TestDigraph::Node *>> grid(ROWS,
1345 std::vector<TestDigraph::Node *>(COLS));
1346
1347 for (size_t r = 0; r < ROWS; ++r)
1348 for (size_t c = 0; c < COLS; ++c)
1349 grid[r][c] = add_node(g, static_cast<int>(r * COLS + c));
1350
1351 // Connect in all 4 directions (bidirectional)
1352 for (size_t r = 0; r < ROWS; ++r)
1353 for (size_t c = 0; c < COLS; ++c)
1354 {
1355 if (c + 1 < COLS)
1356 {
1357 add_arc(g, grid[r][c], grid[r][c + 1]);
1358 add_arc(g, grid[r][c + 1], grid[r][c]);
1359 }
1360 if (r + 1 < ROWS)
1361 {
1362 add_arc(g, grid[r][c], grid[r + 1][c]);
1363 add_arc(g, grid[r + 1][c], grid[r][c]);
1364 }
1365 }
1366
1368
1369 // All nodes in one SCC
1370 EXPECT_EQ(tarjan.num_connected_components(g), 1u);
1371 EXPECT_TRUE(tarjan.has_cycle(g));
1372 EXPECT_TRUE(tarjan.test_connectivity(g));
1373}
1374
1375// ============================================================================
1376// Test: Very deep linear chain (stress test for recursion)
1377// ============================================================================
1378TEST(TarjanExtended, DeepLinearChain)
1379{
1380 TestDigraph g;
1381 const size_t DEPTH = 500; // Deep enough to stress but not overflow
1382
1383 std::vector<TestDigraph::Node *> nodes(DEPTH);
1384 for (size_t i = 0; i < DEPTH; ++i)
1385 nodes[i] = add_node(g, static_cast<int>(i));
1386
1387 for (size_t i = 0; i + 1 < DEPTH; ++i)
1388 add_arc(g, nodes[i], nodes[i + 1]);
1389
1391
1392 EXPECT_EQ(tarjan.num_connected_components(g), DEPTH);
1393 EXPECT_FALSE(tarjan.has_cycle(g));
1394 EXPECT_TRUE(tarjan.is_dag(g));
1395}
1396
1397// ============================================================================
1398// Test: Consistency between different connected_components overloads
1399// ============================================================================
1400TEST(TarjanExtended, ConsistencyBetweenOverloads)
1401{
1402 TestDigraph g;
1403
1404 // Create a complex graph
1405 auto a = add_node(g, 1);
1406 auto b = add_node(g, 2);
1407 auto c = add_node(g, 3);
1408 auto d = add_node(g, 4);
1409 auto e = add_node(g, 5);
1410
1411 // SCC1: {a, b, c}
1412 add_arc(g, a, b);
1413 add_arc(g, b, c);
1414 add_arc(g, c, a);
1415
1416 // SCC2: {d, e}
1417 add_arc(g, d, e);
1418 add_arc(g, e, d);
1419
1420 // Inter-SCC arcs
1421 add_arc(g, b, d);
1422
1424
1425 // Method 1: Get sizes
1426 DynList<size_t> sizes;
1427 tarjan.connected_components(g, sizes);
1428
1429 // Method 2: Get node lists
1430 auto node_lists = tarjan.connected_components(g);
1431
1432 // Method 3: Get blocks with arcs
1433 DynList<TestDigraph> blocks;
1434 DynList<TestDigraph::Arc *> inter_arcs;
1435 tarjan.connected_components(g, blocks, inter_arcs);
1436
1437 // All should report same number of SCCs
1438 EXPECT_EQ(sizes.size(), node_lists.size());
1439 EXPECT_EQ(sizes.size(), blocks.size());
1440 EXPECT_EQ(sizes.size(), 2u);
1441
1442 // Sizes should match
1443 size_t total_from_sizes = 0;
1444 for (auto sz : sizes)
1445 total_from_sizes += sz;
1446
1447 size_t total_from_lists = 0;
1448 for (auto &list : node_lists)
1449 total_from_lists += list.size();
1450
1451 size_t total_from_blocks = 0;
1452 for (auto &block : blocks)
1453 total_from_blocks += block.get_num_nodes();
1454
1455 EXPECT_EQ(total_from_sizes, 5u);
1456 EXPECT_EQ(total_from_lists, 5u);
1457 EXPECT_EQ(total_from_blocks, 5u);
1458
1459 // Inter-SCC arcs
1460 EXPECT_EQ(inter_arcs.size(), 1u);
1461}
1462
1463// ============================================================================
1464// Test: Cycle detection vs SCC count consistency
1465// ============================================================================
1466TEST(TarjanExtended, CycleDetectionConsistency)
1467{
1468 // A graph has a cycle iff some SCC has size > 1 OR some node has self-loop
1469 TestDigraph g;
1470
1471 // 10 isolated nodes (no cycles)
1472 for (int i = 0; i < 10; ++i)
1473 add_node(g, i);
1474
1476
1477 EXPECT_FALSE(tarjan.has_cycle(g));
1478 EXPECT_EQ(tarjan.num_connected_components(g), 10u);
1479
1480 // All SCCs should have size 1
1481 DynList<size_t> sizes;
1482 tarjan.connected_components(g, sizes);
1483 for (auto sz : sizes)
1484 EXPECT_EQ(sz, 1u);
1485}
1486
1487// ============================================================================
1488// Test: Very large strongly connected component
1489// ============================================================================
1490TEST(TarjanExtended, LargeSCC)
1491{
1492 TestDigraph g;
1493 const size_t N = 2000;
1494
1495 std::vector<TestDigraph::Node *> nodes(N);
1496 for (size_t i = 0; i < N; ++i)
1497 nodes[i] = add_node(g, static_cast<int>(i));
1498
1499 // Create cycle: 0 -> 1 -> 2 -> ... -> N-1 -> 0
1500 for (size_t i = 0; i < N; ++i)
1501 add_arc(g, nodes[i], nodes[(i + 1) % N]);
1502
1503 // Add some random cross-edges to make it more connected
1504 for (size_t i = 0; i < N; i += 7)
1505 add_arc(g, nodes[i], nodes[(i + N / 3) % N]);
1506
1508
1509 // All nodes in one SCC
1510 EXPECT_EQ(tarjan.num_connected_components(g), 1u);
1511 EXPECT_TRUE(tarjan.has_cycle(g));
1512 EXPECT_TRUE(tarjan.test_connectivity(g));
1513
1514 // Verify size
1515 DynList<size_t> sizes;
1516 tarjan.connected_components(g, sizes);
1517 EXPECT_EQ(sizes.size(), 1u);
1518 EXPECT_EQ(sizes.get_first(), N);
1519}
1520
1521// ============================================================================
1522// Test: Many small SCCs
1523// ============================================================================
1524TEST(TarjanExtended, ManySmallSCCs)
1525{
1526 TestDigraph g;
1527 const size_t NUM_SCCS = 500;
1528
1529 for (size_t i = 0; i < NUM_SCCS; ++i)
1530 {
1531 auto a = add_node(g, static_cast<int>(i * 2));
1532 auto b = add_node(g, static_cast<int>(i * 2 + 1));
1533 add_arc(g, a, b);
1534 add_arc(g, b, a);
1535 }
1536
1538
1539 EXPECT_EQ(tarjan.num_connected_components(g), NUM_SCCS);
1540 EXPECT_TRUE(tarjan.has_cycle(g));
1541
1542 DynList<size_t> sizes;
1543 tarjan.connected_components(g, sizes);
1544 for (auto sz : sizes)
1545 EXPECT_EQ(sz, 2u);
1546}
1547
1548// ============================================================================
1549// Test: Path finding in cycle
1550// ============================================================================
1551TEST(TarjanExtended, CyclePathDetails)
1552{
1553 TestDigraph g;
1554 auto a = add_node(g, 1);
1555 auto b = add_node(g, 2);
1556 auto c = add_node(g, 3);
1557 auto d = add_node(g, 4);
1558
1559 add_arc(g, a, b);
1560 add_arc(g, b, c);
1561 add_arc(g, c, d);
1562 add_arc(g, d, b); // cycle: b -> c -> d -> b
1563
1565
1566 Path<TestDigraph> path(g);
1567 bool found = tarjan.compute_cycle(g, path);
1568
1569 ASSERT_TRUE(found);
1570
1571 // Verify cycle: first == last
1572 EXPECT_EQ(path.get_first_node(), path.get_last_node());
1573
1574 // Verify path length (at least 2 nodes for a cycle representation)
1575 size_t len = 0;
1576 for (Path<TestDigraph>::Iterator it(path); it.has_curr(); it.next())
1577 ++len;
1578 EXPECT_GE(len, 2u);
1579}
1580
1581// ============================================================================
1582// Test: Empty graph edge cases
1583// ============================================================================
1584TEST(TarjanExtended, EmptyGraphEdgeCases)
1585{
1586 TestDigraph g;
1588
1589 // Multiple calls on empty graph should all work
1590 EXPECT_EQ(tarjan.num_connected_components(g), 0u);
1591 EXPECT_FALSE(tarjan.has_cycle(g));
1592 EXPECT_TRUE(tarjan.is_dag(g));
1593 EXPECT_TRUE(tarjan.test_connectivity(g));
1594
1596 tarjan.connected_components(g, node_lists);
1597 EXPECT_TRUE(node_lists.is_empty());
1598
1599 DynList<size_t> sizes;
1600 tarjan.connected_components(g, sizes);
1601 EXPECT_TRUE(sizes.is_empty());
1602}
1603
1604// ============================================================================
1605// Test: Graph with parallel arcs (multi-edges)
1606// ============================================================================
1607TEST(TarjanExtended, ParallelArcs)
1608{
1609 TestDigraph g;
1610 auto a = add_node(g, 1);
1611 auto b = add_node(g, 2);
1612
1613 // Multiple arcs in same direction
1614 add_arc(g, a, b);
1615 add_arc(g, a, b);
1616 add_arc(g, a, b);
1617
1619
1620 // Still 2 SCCs (no back edge)
1621 EXPECT_EQ(tarjan.num_connected_components(g), 2u);
1622 EXPECT_FALSE(tarjan.has_cycle(g));
1623
1624 // Add back edges
1625 add_arc(g, b, a);
1626 add_arc(g, b, a);
1627
1629 EXPECT_EQ(tarjan2.num_connected_components(g), 1u);
1630 EXPECT_TRUE(tarjan2.has_cycle(g));
1631}
1632
1633// ============================================================================
1634// Test: Tournament graph (complete asymmetric digraph)
1635// ============================================================================
1636TEST(TarjanExtended, TournamentGraph)
1637{
1638 TestDigraph g;
1639 const size_t N = 8;
1640
1641 std::vector<TestDigraph::Node *> nodes(N);
1642 for (size_t i = 0; i < N; ++i)
1643 nodes[i] = add_node(g, static_cast<int>(i));
1644
1645 // Tournament: for each pair (i,j) with i < j, add exactly one arc
1646 // Direction based on some pattern
1647 for (size_t i = 0; i < N; ++i)
1648 for (size_t j = i + 1; j < N; ++j)
1649 {
1650 if ((i + j) % 2 == 0)
1651 add_arc(g, nodes[i], nodes[j]);
1652 else
1653 add_arc(g, nodes[j], nodes[i]);
1654 }
1655
1657
1658 // Tournament graphs are interesting - may or may not be strongly connected
1659 // Just verify the algorithm completes successfully
1660 size_t num_sccs = tarjan.num_connected_components(g);
1661 EXPECT_GE(num_sccs, 1u);
1662 EXPECT_LE(num_sccs, N);
1663}
1664
1665// ============================================================================
1666// Test: Dense random-like graph
1667// ============================================================================
1668TEST(TarjanExtended, DenseGraph)
1669{
1670 TestDigraph g;
1671 const size_t N = 50;
1672
1673 std::vector<TestDigraph::Node *> nodes(N);
1674 for (size_t i = 0; i < N; ++i)
1675 nodes[i] = add_node(g, static_cast<int>(i));
1676
1677 // Add many edges based on a pattern
1678 for (size_t i = 0; i < N; ++i)
1679 for (size_t j = 0; j < N; ++j)
1680 if (i != j && (i * 7 + j * 3) % 5 < 3) // ~60% edge density
1681 add_arc(g, nodes[i], nodes[j]);
1682
1684
1685 // Just verify it completes and gives consistent results
1686 auto sccs = tarjan.connected_components(g);
1687 size_t total = 0;
1688 for (auto &scc : sccs)
1689 total += scc.size();
1690 EXPECT_EQ(total, N);
1691}
1692
1693// ============================================================================
1694// Test: Compute_Cycle_In_Digraph with no cycle
1695// ============================================================================
1696TEST(TarjanExtended, ComputeCycleNoCycle)
1697{
1698 TestDigraph g;
1699 auto a = add_node(g, 1);
1700 auto b = add_node(g, 2);
1701 auto c = add_node(g, 3);
1702 add_arc(g, a, b);
1703 add_arc(g, b, c);
1704
1706
1707 Path<TestDigraph> path(g);
1708 bool found = finder(g, path);
1709 EXPECT_FALSE(found);
1710
1711 auto path2 = finder(g);
1712 EXPECT_TRUE(path2.is_empty());
1713
1714 auto path3 = finder(g, a);
1715 EXPECT_TRUE(path3.is_empty());
1716}
1717
1718// ============================================================================
1719// Test: the frames of a search do not outlive it
1720// ============================================================================
1721namespace
1722{
1723 // Shows every arc, and counts its copies that live: one in the object,
1724 // and one in each frame of a search that waits
1725 struct Counted_Copies
1726 {
1727 static inline long alive = 0;
1728
1729 Counted_Copies() noexcept { ++alive; }
1730 Counted_Copies(const Counted_Copies &) noexcept { ++alive; }
1731 Counted_Copies & operator = (const Counted_Copies &) noexcept = default;
1732 ~Counted_Copies() { --alive; }
1733
1734 bool operator()(TestDigraph::Arc *) const noexcept { return true; }
1735 };
1736}
1737
1738// The stack of a search is of the search: an object that lives keeps no
1739// frame, and no room for them, after an operation, even after one that
1740// stops early with the frames of a path as long as the graph in the stack
1741// (#26 of the 7.3.2 review: a member kept them until the next search)
1742TEST(TarjanTest, KeepsNoFrameAfterAnOperation)
1743{
1744 // a chain whose last node goes back to the one before it: the cycle is
1745 // found at the end of the chain, from which the search stops
1746 TestDigraph g;
1747 const int n = 5000;
1748 std::vector<TestDigraph::Node *> nodes;
1749 for (int i = 0; i < n; ++i)
1750 nodes.push_back(add_node(g, i));
1751 for (int i = 0; i + 1 < n; ++i)
1752 add_arc(g, nodes[i], nodes[i + 1]);
1753 add_arc(g, nodes[n - 1], nodes[n - 2]);
1754
1755 Counted_Copies::alive = 0;
1756 {
1758 const long kept = Counted_Copies::alive; // that of the object
1759
1760 EXPECT_TRUE(tarjan.has_cycle(g));
1761 EXPECT_EQ(Counted_Copies::alive, kept);
1762
1763 Path<TestDigraph> cycle(g);
1764 EXPECT_TRUE(tarjan.compute_cycle(g, cycle));
1765 EXPECT_EQ(cycle.size(), 3u); // n - 2, n - 1 and n - 2 again
1766 EXPECT_EQ(Counted_Copies::alive, kept);
1767
1768 EXPECT_FALSE(tarjan.test_connectivity(g));
1769 EXPECT_EQ(Counted_Copies::alive, kept);
1770
1771 EXPECT_EQ(tarjan.num_connected_components(g), size_t(n - 1));
1772 EXPECT_EQ(Counted_Copies::alive, kept);
1773 }
1774 EXPECT_EQ(Counted_Copies::alive, 0);
1775}
Tarjan's algorithm for strongly connected components.
size_t size_t int32_t value
Definition ca-c-api.h:116
Determines if a digraph contains a cycle and constructs it.
Definition Tarjan.H:1105
auto has_curr() const noexcept(noexcept(std::declval< I & >().has_curr())) -> decltype(std::declval< I & >().has_curr())
true if there is a current item.
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
typename BaseGraph::Arc Arc
Definition graph-dry.H:4381
typename BaseGraph::Node Node
Definition graph-dry.H:4380
Dynamic doubly linked list with O(1) size and bidirectional access.
const size_t & size() const noexcept
Return the number of elements (constant time)
T & get_first()
Return a modifiable reference to first item in the list.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & get_first()
Return the first item of the list.
Definition htlist.H:1548
T & append(const T &item)
Definition htlist.H:1362
size_t size() const noexcept
Return the number of items of the list, in constant time.
Definition htlist.H:1264
constexpr bool is_empty() const noexcept
Definition htlist.H:434
Number Theoretic Transform over Z / MOD Z.
Definition ntt.H:115
Iterator on nodes and arcs of a path.
Definition tpl_graph.H:4395
Path on a graph.
Definition tpl_graph.H:3832
size_t size() const noexcept
Return the path length in nodes.
Definition tpl_graph.H:3987
Node * get_first_node() const
Return the first node of path; throws overflow_error if path is empty.
Definition tpl_graph.H:4316
bool is_empty() const noexcept
Return true if the path is empty.
Definition tpl_graph.H:3993
Node * get_last_node() const
Return the last node of path; throws overflow_error if path is empty.
Definition tpl_graph.H:4323
Computes strongly connected components (SCCs) in a directed graph using Tarjan's algorithm.
Definition Tarjan.H:174
bool has_computation() const noexcept
Check if a computation has been performed.
Definition Tarjan.H:1067
SA & get_filter() noexcept
Returns the arc filter used by this instance.
Definition Tarjan.H:1051
bool has_cycle(typename GT::Node *root)
Depth-first search that detects a cycle reachable from root.
Definition Tarjan.H:547
bool test_connectivity(const GT &g)
Tests whether the digraph is strongly connected.
Definition Tarjan.H:1022
void connected_components(const GT &g, DynList< GT > &blk_list, DynList< typename GT::Arc * > &arc_list)
Computes the strongly connected components (SCCs) of a digraph.
Definition Tarjan.H:721
bool compute_cycle(const GT &g, Path< GT > &path)
Finds and constructs a cycle in the digraph, if one exists.
Definition Tarjan.H:972
GT * get_graph() const noexcept
Get the graph of the last computation.
Definition Tarjan.H:1075
bool is_dag(const GT &g)
Determines whether the directed graph is acyclic (a DAG).
Definition Tarjan.H:954
size_t num_connected_components(const GT &g)
Returns the number of strongly connected components in the graph.
Definition Tarjan.H:814
Minimal std::expected-style result type for C++20.
#define TEST(name)
#define N
Definition fib.C:294
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
Main namespace for Aleph-w library functions.
Container2< typename Container1::Item_Type > filter(Container1 &container, Operation &operation)
Filter elements that satisfy operation.
bool between(const Point &a, const Point &b, const Point &c)
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
bool operator()(TestDigraph::Arc *a) const noexcept
TestDigraph::Arc * add_arc(TestDigraph &g, TestDigraph::Node *src, TestDigraph::Node *tgt, int value=0)
TestDigraph::Node * add_node(TestDigraph &g, int value)
DynList< int > l1
DynList< int > l2
Gsl_Compatible_Rng r
Generic graph and digraph implementations.