Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
graph_kinds_algorithms_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
43#include <gtest/gtest.h>
44
45#include <vector>
46
47#include <Bellman_Ford.H>
48#include <Dijkstra.H>
49#include <Floyd_Warshall.H>
50#include <Johnson.H>
51#include <Tarjan.H>
52#include <kosaraju.H>
53#include <topological_sort.H>
54#include <tpl_agraph.H>
55#include <tpl_components.H>
56#include <tpl_cut_nodes.H>
57#include <tpl_find_path.H>
58#include <tpl_graph.H>
59#include <tpl_graph_utils.H>
60#include <tpl_sgraph.H>
61#include <tpl_test_acyclique.H>
62#include <tpl_test_cycle.H>
63#include <tpl_test_path.H>
64
65using namespace Aleph;
66
67namespace
68{
69 // The weight of the arcs of a path
70 template <class GT>
71 int weight_of(const Path<GT> & path)
72 {
73 int w = 0;
74 for (typename Path<GT>::Iterator it(path); it.has_curr(); it.next_ne())
75 if (it.has_current_arc())
76 w += it.get_current_arc_ne()->get_info();
77 return w;
78 }
79
80 // A cycle 0..5, a tail 5-6-7 and a triangle 7-8-9, with the weights of
81 // the arcs; the arc 0-5 weighs more than the rest of the cycle
82 template <class GT>
83 std::vector<typename GT::Node *> build(GT & g)
84 {
85 std::vector<typename GT::Node *> v;
86 for (int i = 0; i < 10; ++i)
87 v.push_back(g.insert_node(i));
88 for (int i = 0; i < 5; ++i)
89 g.insert_arc(v[i], v[i + 1], 1);
90 g.insert_arc(v[5], v[0], 10);
91 g.insert_arc(v[5], v[6], 2);
92 g.insert_arc(v[6], v[7], 2);
93 g.insert_arc(v[7], v[8], 3);
94 g.insert_arc(v[8], v[9], 3);
95 g.insert_arc(v[9], v[7], 3);
96 return v;
97 }
98
99 template <class GT>
100 struct UndirectedKinds : public ::testing::Test {};
101
102 template <class GT>
103 struct DirectedKinds : public ::testing::Test {};
104
105 using Undirected =
106 ::testing::Types<List_Graph<Graph_Node<int>, Graph_Arc<int>>,
109
110 using Directed =
111 ::testing::Types<List_Digraph<Graph_Node<int>, Graph_Arc<int>>,
114}
115
116TYPED_TEST_SUITE(UndirectedKinds, Undirected);
117TYPED_TEST_SUITE(DirectedKinds, Directed);
118
119TYPED_TEST(UndirectedKinds, CutNodesAndBridges)
120{
121 using GT = TypeParam;
122 GT g;
123 auto v = build(g);
124
126 Compute_Cut_Nodes<GT> cut_nodes(g);
127 cut_nodes(v[0], cuts);
128 EXPECT_EQ(cuts.size(), 3u); // 5, 6 and 7
129 EXPECT_EQ(compute_cut_nodes(g, v[0]).size(), 3u);
130 EXPECT_EQ(find_bridges(g, v[0]).size(), 2u); // 5-6 and 6-7
131}
132
133TYPED_TEST(UndirectedKinds, TraversalsAndComponents)
134{
135 using GT = TypeParam;
136 GT g;
137 auto v = build(g);
138 g.insert_node(10); // alone
139
140 EXPECT_EQ(depth_first_traversal<GT>(g, v[0], nullptr), 10u);
141 EXPECT_EQ(Depth_First_Traversal<GT>()(g, v[0]), 10u);
142 EXPECT_EQ(breadth_first_traversal<GT>(g, v[0], nullptr), 10u);
143 EXPECT_EQ(Unconnected_Components<GT>().count_components(g), 2u);
144 EXPECT_EQ(inconnected_components(g).size(), 2u);
145}
146
147TYPED_TEST(UndirectedKinds, PathsAndCycles)
148{
149 using GT = TypeParam;
150 GT g;
151 auto v = build(g);
152
153 Path<GT> dfs_path(g);
154 ASSERT_TRUE(Find_Path_Depth_First<GT>()(g, v[1], v[9], dfs_path));
155 EXPECT_EQ(dfs_path.get_first_node(), v[1]);
156 EXPECT_EQ(dfs_path.get_last_node(), v[9]);
157 Path<GT> bfs_path(g);
158 ASSERT_TRUE(Find_Path_Breadth_First<GT>()(g, v[1], v[9], bfs_path));
159 EXPECT_EQ(bfs_path.size(), 6u); // 1 0 5 6 7 9
160
161 EXPECT_TRUE(test_for_path(g, v[1], v[9]));
162 EXPECT_TRUE(test_for_cycle(g, v[0]));
163 EXPECT_FALSE(test_for_cycle(g, v[6]));
164 EXPECT_FALSE(is_graph_acyclique(g));
165 EXPECT_TRUE(Test_For_Cycle<GT>()(g, v[8]));
166 EXPECT_TRUE(Test_For_Path<GT>()(g, v[1], v[9]));
167}
168
169TYPED_TEST(UndirectedKinds, ShortestPaths)
170{
171 using GT = TypeParam;
172 GT g;
173 auto v = build(g);
174
175 Path<GT> path(g);
176 EXPECT_EQ(Dijkstra_Min_Paths<GT>().find_min_path(g, v[0], v[9], path), 12);
177 EXPECT_EQ(weight_of(path), 12); // 0 1 2 3 4 5 6 7 9
178
180 EXPECT_EQ(weight_of(floyd.get_min_path(v[0], v[9])), 12);
181}
182
183TYPED_TEST(DirectedKinds, StronglyConnectedComponents)
184{
185 using GT = TypeParam;
186 GT g;
187 build(g);
188
189 EXPECT_EQ(Tarjan_Connected_Components<GT>().num_connected_components(g), 3u);
191 EXPECT_EQ(kosaraju_connected_components(g).size(), 3u);
192 DynList<GT> blocks;
195 EXPECT_EQ(blocks.size(), 3u);
196 EXPECT_EQ(between.size(), 2u);
197}
198
199TYPED_TEST(DirectedKinds, TopologicalSort)
200{
201 using GT = TypeParam;
202 GT g;
203 std::vector<typename GT::Node *> v;
204 for (int i = 0; i < 6; ++i)
205 v.push_back(g.insert_node(i));
206 g.insert_arc(v[0], v[1], 1);
207 g.insert_arc(v[0], v[2], 1);
208 g.insert_arc(v[1], v[3], 1);
209 g.insert_arc(v[2], v[3], 1);
210 g.insert_arc(v[3], v[4], 1);
211 g.insert_arc(v[5], v[4], 1);
212
213 auto check = [&g, &v](const auto & order)
214 {
215 ASSERT_EQ(order.size(), v.size());
216 std::vector<size_t> position(v.size());
217 size_t i = 0;
218 for (auto it = order.get_it(); it.has_curr(); it.next_ne())
219 position[size_t(it.get_curr()->get_info())] = i++;
220 for (typename GT::Arc_Iterator it(g); it.has_curr(); it.next_ne())
221 EXPECT_LT(position[size_t(g.get_src_node(it.get_curr())->get_info())],
222 position[size_t(g.get_tgt_node(it.get_curr())->get_info())]);
223 };
224 check(Topological_Sort<GT>().template perform<DynList>(g));
225 check(Q_Topological_Sort<GT>().template perform<DynList>(g));
226}
227
228TYPED_TEST(DirectedKinds, ShortestPaths)
229{
230 using GT = TypeParam;
231 GT g;
232 auto v = build(g);
233
234 Path<GT> path(g);
235 EXPECT_EQ(Dijkstra_Min_Paths<GT>().find_min_path(g, v[0], v[9], path), 15);
236 EXPECT_EQ(weight_of(path), 15); // 0 1 2 3 4 5 6 7 8 9
237
238 Bellman_Ford<GT> bf(g);
239 ASSERT_FALSE(bf.paint_spanning_tree(v[0])); // no negative cycle
240 Path<GT> bf_path(g);
241 EXPECT_EQ(bf.get_min_path(v[9], bf_path), 15);
242
244 EXPECT_EQ(weight_of(floyd.get_min_path(v[0], v[9])), 15);
245
246 Johnson<GT> johnson(g);
247 EXPECT_EQ(johnson.get_distance(v[0], v[9]), 15);
248}
Bellman-Ford algorithm for single-source shortest paths.
Dijkstra's shortest path algorithm.
Floyd-Warshall algorithm for all-pairs shortest paths.
Johnson's algorithm for all-pairs shortest paths.
Tarjan's algorithm for strongly connected components.
long double w
Definition btreepic.C:153
Bellman-Ford algorithm for shortest paths with negative weights.
bool paint_spanning_tree(Node *start)
Paint the shortest paths tree from a start node.
Distance_Type get_min_path(typename GT::Node *end, Path< GT > &path)
Extract the shortest path to a node from a previously painted tree.
Computation of cut nodes (articulation points) of a graph.
auto has_curr() const noexcept(noexcept(std::declval< I & >().has_curr())) -> decltype(std::declval< I & >().has_curr())
true if there is a current item.
Stateful depth-first traversal functor.
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
Spanning tree calculation of all shortest paths from a given node according to Dijkstra's algorithm.
Definition Dijkstra.H:117
Dynamic doubly linked list with O(1) size and bidirectional access.
const size_t & size() const noexcept
Return the number of elements (constant time)
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
size_t size() const noexcept
Return the number of items of the list, in constant time.
Definition htlist.H:1264
Performs a breadth-first search for a path between a pair of nodes.
Performs a depth-first search for a path between a pair of nodes.
Compute the all-pairs shortest path distance matrix and the path reconstruction matrix for a graph g ...
Path< GT > get_min_path(const long src_idx, const long tgt_idx) const
Reconstruct the shortest path between two nodes by matrix indices.
Arc for graphs implemented with simple adjacency lists.
Definition tpl_sgraph.H:197
Johnson's algorithm for all-pairs shortest paths.
Definition Johnson.H:216
Distance_Type get_distance(Node *src, Node *tgt)
Get the shortest distance from source to target.
Definition Johnson.H:885
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Definition tpl_graph.H:535
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Definition tpl_graph.H:618
Graph class implemented with singly-linked adjacency lists.
Definition tpl_sgraph.H:274
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
Node * get_last_node() const
Return the last node of path; throws overflow_error if path is empty.
Definition tpl_graph.H:4323
Computes topological ordering using breadth-first search (Kahn's algorithm).
Computes strongly connected components (SCCs) in a directed graph using Tarjan's algorithm.
Definition Tarjan.H:174
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
Test whether a cycle is reachable from a given node.
Checks whether a path exists between two nodes.
Computes topological ordering using depth-first search.
Compute the connected components of a graph.
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Definition graph-dry.H:1017
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
TYPED_TEST(UndirectedKinds, CutNodesAndBridges)
TYPED_TEST_SUITE(UndirectedKinds, Undirected)
bool has_cycle(const GT &g)
Return true if an undirected graph has at least one cycle.
void kosaraju_connected_components(const GT &g, DynList< GT > &blk_list, DynList< typename GT::Arc * > &arc_list)
Compute strongly connected components using Kosaraju's algorithm.
Definition kosaraju.H:267
DynList< GT > inconnected_components(const GT &g)
Forward declaration for inconnected_components().
bool test_for_cycle(const GT &g, typename GT::Node *src)
Search for a cycle reachable from a given node.
DynList< typename GT::Node * > compute_cut_nodes(const GT &g, typename GT::Node *start)
Compute articulation points (cut vertices) of an undirected graph.
bool test_for_path(const GT &g, typename GT::Node *start_node, typename GT::Node *end_node)
Return true if there is a path between two nodes.
DynList< typename GT::Arc * > find_bridges(const GT &g, typename GT::Node *start, SA sa=SA())
Find all bridge edges in a connected undirected graph.
bool is_graph_acyclique(const GT &g, typename GT::Node *start_node)
Return true if an undirected graph is acyclic.
void find_min_path(Mat &p, long src_idx, long tgt_idx, Path< typename Mat::Graph_Type > &path)
Build a minimum path from Floyd-Warshall path matrix using indices.
Definition mat_path.H:191
Kosaraju's algorithm for finding strongly connected components.
void build(Tree_Node< Key > *troot, Convert &&convert, typename GT::Node *groot, Args &&... args)
Main namespace for Aleph-w library functions.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
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 check(GT &g)
Topological sorting algorithms for directed acyclic graphs (DAGs).
Array-based graph implementation.
Graph connectivity and connected components.
Articulation points (cut nodes), bridges, and biconnected components.
Path finding algorithms in graphs.
Generic graph and digraph implementations.
Utility algorithms and operations for graphs.
Simple graph implementation with adjacency lists.
DAG (acyclic) graph testing.
Cycle detection in graphs.
Path existence testing.