Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_spanning_tree.H
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
52# ifndef TPL_SPANNING_TREE_H
53# define TPL_SPANNING_TREE_H
54
55# include <ah-graph-concepts.H>
56
57# include <tpl_dfs_stack.H>
58# include <tpl_graph.H>
59# include <tpl_graph_utils.H>
60# include <ah-errors.H>
61
62namespace Aleph {
63
115template <AlephGraph GT, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
117{
118 SA sa;
119 GT * gptr = nullptr;
120 GT * tptr = nullptr;
121
122 // A node of the tree that waits for the one that it visits, its image
123 // in the tree, and the next arc of it to look at
124 struct Frame
125 {
126 typename GT::Node * tnode;
128
129 [[gnu::always_inline]] ALEPH_FLATTEN
130 Frame(typename GT::Node * gnode, typename GT::Node * image, SA & sa)
131 : tnode(image), it(gnode, sa) {}
132
133 [[gnu::always_inline]] ALEPH_FLATTEN
134 void next_arc() noexcept(noexcept(it.next_ne())) { it.next_ne(); }
135
136 // Moves the iterator, while the tree is not complete, to the next arc
137 // not in the tree whose target is not in the tree either, and gives
138 // that target; nullptr when the arcs are done or the tree is complete
139 [[gnu::always_inline]] ALEPH_FLATTEN typename GT::Node *
140 next_target(const GT & tree, const GT & g) noexcept(noexcept(it.next_ne()))
141 {
142 for (; it.has_curr() and tree.get_num_nodes() < g.get_num_nodes(); it.next_ne())
143 {
144 auto arc = it.get_current_arc_ne();
146 continue;
147
148 auto arc_tgt_node = it.get_tgt_node_ne();
149 if (not IS_NODE_VISITED(arc_tgt_node, Spanning_Tree))
150 return arc_tgt_node; // Target not visited through another arc
151 }
152 return nullptr;
153 }
154 };
155
156 // Puts gnode in the tree, reached through garc from the node whose image
157 // is tnode, and gives the image of gnode, or nullptr if the tree is
158 // complete
159 [[gnu::always_inline]]
160 typename GT::Node * put_in_tree(typename GT::Node * gnode, typename GT::Arc * garc,
161 typename GT::Node * tnode)
162 {
163 // Mark node and arc as part of spanning tree
164 NODE_BITS(gnode).set_bit(Spanning_Tree, true);
165 ARC_BITS(garc).set_bit(Spanning_Tree, true);
166
167 // Create corresponding node in tree and establish mapping
168 auto tree_tgt_node = tptr->insert_node(gnode->get_info());
169 GT::map_nodes(gnode, tree_tgt_node);
170
171 // Create corresponding arc in tree and establish mapping
172 auto tarc = tptr->insert_arc(tnode, tree_tgt_node, garc->get_info());
173 GT::map_arcs(garc, tarc);
174
175 // Check if spanning tree is complete (all nodes covered)
177 return nullptr;
178
179 // Invariant: tree must be acyclic (nodes > arcs)
180 assert(tptr->get_num_nodes() > tptr->get_num_arcs());
181 return tree_tgt_node;
182 }
183
184 // DFS helper to build the spanning tree. A path can have as many nodes
185 // as the graph, too many for recursion, so that the search keeps its own
186 // stack; the order of the visits is that of a recursion.
187 bool build_tree(typename GT::Node * gnode, typename GT::Arc * garc,
188 typename GT::Node * tnode)
189 {
190 auto image = put_in_tree(gnode, garc, tnode);
191 if (image == nullptr)
192 return true;
193
194 // Explore adjacent nodes via DFS. The node being visited keeps its
195 // iterator in here until it visits a node; then it waits in frames,
196 // where it goes on when it comes back. here is optional, so that the
197 // frame of each node is built in its place: a frame keeps the filter,
198 // which may not be assignable.
199 Dfs_Stack<Frame> frames;
200 std::optional<Frame> here(std::in_place, gnode, image, sa);
201 while (true)
202 {
203 if (auto tgt = here->next_target(*tptr, *gptr))
204 { // the iterator stays on the arc to tgt, as in a recursion
205 image = put_in_tree(tgt, here->it.get_current_arc_ne(), here->tnode);
206 if (image == nullptr)
207 return true;
208
209 frames.push(std::move(*here));
210 here.emplace(tgt, image, sa);
211 continue;
212 }
213
214 while (true) // back to the nodes that wait
215 {
216 if (frames.is_empty())
217 return false;
218
219 Frame & f = frames.top();
220 f.next_arc(); // past the arc to the node that was visited
221 if (auto tgt = f.next_target(*tptr, *gptr))
222 {
223 image = put_in_tree(tgt, f.it.get_current_arc_ne(), f.tnode);
224 if (image == nullptr)
225 return true;
226
227 here.emplace(tgt, image, sa);
228 break;
229 }
230 frames.pop();
231 }
232 }
233 }
234
235 // Main algorithm entry point
236 bool build_tree(GT & g, typename GT::Node * gnode, GT & tree)
237 {
238 gptr = &g;
239 tptr = &tree;
240
241 // Reset all control bits for fresh traversal
242 gptr->reset_nodes();
243 gptr->reset_arcs();
244
245 // Ensure output tree is empty
247
248 // Mark starting node as visited
249 NODE_BITS(gnode).set_bit(Spanning_Tree, true);
250
251 // Create root node in tree and establish mapping
252 auto tnode = tree.insert_node(gnode->get_info());
253 GT::map_nodes(gnode, tnode);
254
255 // Explore all adjacent arcs via DFS
256 for (Node_Arc_Iterator<GT, SA> i(gnode, sa);
257 i.has_curr() and tptr->get_num_nodes() < gptr->get_num_nodes();
258 i.next_ne())
259 {
260 auto arc = i.get_current_arc_ne();
261 if (IS_ARC_VISITED(arc, Spanning_Tree))
262 continue;
263
264 auto arc_tgt_node = i.get_tgt_node();
265 if (IS_NODE_VISITED(arc_tgt_node, Spanning_Tree))
266 continue; // Target already visited via another arc
267
268 if (build_tree(arc_tgt_node, arc, tnode))
269 return true; // every node is in the tree
270 }
271
272 // whether the tree spans g, which it does not if g is not connected
273 return tptr->get_num_nodes() == gptr->get_num_nodes();
274 }
275
276public:
277
283 Find_Depth_First_Spanning_Tree(SA arc_filter = SA()) : sa(arc_filter) { /* empty */ }
284
303 typename GT::Node * operator () (GT & g, GT & tree)
304 {
306 << "Find_Depth_First_Spanning_Tree: graph is empty";
307
308 auto start = g.get_first_node();
309 if (not build_tree(g, start, tree))
310 return nullptr;
311
312 return start;
313 }
314
332 typename GT::Node * operator () (GT & g, typename GT::Node * gnode, GT & tree)
333 {
334 ah_invalid_argument_if(gnode == nullptr)
335 << "Find_Depth_First_Spanning_Tree: source node cannot be null";
336
337 this->build_tree(g, gnode, tree);
338 return static_cast<typename GT::Node *>(NODE_COOKIE(gnode));
339 }
340};
341
342
387template <AlephGraph GT, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
389{
390 SA sa;
391
392 // Main BFS algorithm to build spanning tree
393 void build_tree(GT & g, typename GT::Node * gp, GT & tree)
394 {
395 // Reset control bits for fresh traversal
398
399 // Ensure output tree is empty
400 clear_graph(tree);
401
402 // Create root node in tree and establish mapping; the cookie is
403 // cleared, else the mapping would compose with a former tree
404 auto tp = tree.insert_node(gp->get_info());
405 NODE_COOKIE(gp) = nullptr;
406 GT::map_nodes(gp, tp);
407
408 // Initialize queue with arcs adjacent to starting node
410 for (Node_Arc_Iterator<GT, SA> i(gp, sa); i.has_curr(); i.next_ne())
411 q.put(i.get_current_arc_ne());
412
413 // Mark starting node as visited
414 NODE_BITS(gp).set_bit(Spanning_Tree, true);
415
416 // BFS loop
417 while (not q.is_empty())
418 {
419 auto garc = q.get();
420 ARC_BITS(garc).set_bit(Spanning_Tree, true);
421 auto gsrc = g.get_src_node(garc);
422 auto gtgt = g.get_tgt_node(garc);
423
424 // Skip if both endpoints already visited
427 continue;
428
429 // Ensure gsrc is the visited node and gtgt is the new one
431 std::swap(gsrc, gtgt);
432
433 auto tsrc = mapped_node<GT>(gsrc);
434 NODE_BITS(gtgt).set_bit(Spanning_Tree, true);
435
436 // Create new node in tree and establish mapping
437 auto ttgt = tree.insert_node(gtgt->get_info());
438 NODE_COOKIE(gtgt) = nullptr;
439 GT::map_nodes(gtgt, ttgt);
440
441 // Create new arc in tree and establish mapping
442 auto tarc = tree.insert_arc(tsrc, ttgt, garc->get_info());
443 ARC_COOKIE(garc) = nullptr;
444 GT::map_arcs(garc, tarc);
445
446 // Check if spanning tree is complete
447 if (tree.get_num_nodes() == g.get_num_nodes())
448 break;
449
450 // Enqueue arcs adjacent to newly added node
451 for (Node_Arc_Iterator<GT, SA> i(gtgt, sa); i.has_curr(); i.next_ne())
452 {
453 auto current_arc = i.get_current_arc_ne();
454 if (IS_ARC_VISITED(current_arc, Spanning_Tree))
455 continue;
456
457 // Skip arcs where both endpoints are already visited
458 if (IS_NODE_VISITED(g.get_src_node(current_arc), Spanning_Tree) and
460 continue;
461 q.put(current_arc);
462 }
463 }
464 }
465
466public:
467
473 Find_Breadth_First_Spanning_Tree(SA arc_filter = SA()) : sa(arc_filter) { /* empty */ }
474
492 void operator () (GT & g, typename GT::Node * gnode, GT & tree)
493 {
494 ah_invalid_argument_if(gnode == nullptr)
495 << "Find_Breadth_First_Spanning_Tree: source node cannot be null";
496
497 this->build_tree(g, gnode, tree);
498 }
499
512 typename GT::Node * operator () (GT & g, GT & tree)
513 {
515 << "Find_Breadth_First_Spanning_Tree: graph is empty";
516
517 auto start = g.get_first_node();
518 this->build_tree(g, start, tree);
519 return static_cast<typename GT::Node *>(NODE_COOKIE(start));
520 }
521};
522
542template <AlephGraph GT>
544{
545public:
546
557 {
558 return build_spanning_tree<GT>(arcs);
559 }
560
572 {
573 ah_invalid_argument_if(arcs == nullptr)
574 << "Build_Spanning_Tree: arcs array cannot be null";
575 return build_spanning_tree<GT>(*arcs);
576 }
577};
578
579} // end namespace Aleph
580
581# endif // TPL_SPANNING_TREE_H
Exception handling system with formatted messages for Aleph-w.
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
Definition ah-errors.H:787
C++20 concepts for the protocol shared by graph algorithms.
EepicNode< long > * build_tree()
Definition btreepic.C:1434
Build a spanning tree from an array of arcs.
GT operator()(const DynArray< typename GT::Arc * > &arcs) const
Construct spanning tree from array of arc pointers.
Stack of the frames of a depth-first search that does not recurse.
T & push(Args &&...args)
Builds a frame on top of the stack.
bool is_empty() const noexcept
Whether the stack has no frames.
T & top() noexcept
The top frame; the stack must not be empty.
void pop() noexcept
Destroys the top frame; the stack must not be empty.
Dynamic queue of elements of generic type T based on single linked list.
T & put(const T &data)
The type of element.
T get()
Remove the oldest item of the queue.
bool is_empty() const noexcept
Return true if this is empty.
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
Compute a breadth-first spanning tree of a graph.
void build_tree(GT &g, typename GT::Node *gp, GT &tree)
void operator()(GT &g, typename GT::Node *gnode, GT &tree)
Build a breadth-first spanning tree starting from a specific node.
Find_Breadth_First_Spanning_Tree(SA arc_filter=SA())
Construct a BFS spanning tree builder with optional arc filter.
Compute a depth-first spanning tree of a graph.
GT::Node * operator()(GT &g, GT &tree)
Build a depth-first spanning tree starting from the first node.
Find_Depth_First_Spanning_Tree(SA arc_filter=SA())
Construct a DFS spanning tree builder with optional arc filter.
bool build_tree(typename GT::Node *gnode, typename GT::Arc *garc, typename GT::Node *tnode)
bool build_tree(GT &g, typename GT::Node *gnode, GT &tree)
GT::Node * put_in_tree(typename GT::Node *gnode, typename GT::Arc *garc, typename GT::Node *tnode)
Node * get_first_node() const
Return any node in the graph.
Definition tpl_graph.H:590
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
ArcInfo & get_info() noexcept
Return a modifiable reference to the arc data.
Definition graph-dry.H:854
NodeInfo & get_info() noexcept
Return a modifiable reference to the data contained in the node.
Definition graph-dry.H:753
void reset_bit_nodes(int bit) const noexcept
Reset bit to zero for all the nodes of graph.
Definition graph-dry.H:1326
void reset_arcs() const
Reset all the arcs of graph (the control bits, the state, the counter and the cookie)
Definition graph-dry.H:1213
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
Definition graph-dry.H:975
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Definition graph-dry.H:1017
static void map_arcs(A1 *p, A2 *q) noexcept
Map the arcs through their cookies.
Definition graph-dry.H:1312
void reset_bit_arcs(int bit) const noexcept
Reset bit to zero for all the arcs of graph.
Definition graph-dry.H:1332
constexpr size_t get_num_arcs() const noexcept
Return the number of arcs of the graph.
Definition graph-dry.H:1064
void reset_nodes() const
Reset all the nodes of graph (the control bits, the state, the counter and the cookie)
Definition graph-dry.H:1206
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
static void map_nodes(N1 *p, N2 *q) noexcept
Map the nodes through their cookies.
Definition graph-dry.H:1281
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
#define ARC_COOKIE(p)
Return the arc cookie
#define IS_NODE_VISITED(p, bit)
Determine whether the control bit is set or not to one.
#define ARC_BITS(p)
Return the control bits of arc p.
#define NODE_COOKIE(p)
Return the node cookie
void clear_graph(GT &g)
Clean a graph: all its nodes and arcs are removed and freed.
Definition tpl_graph.H:4776
#define IS_ARC_VISITED(p, bit)
Determine whether the bit field is or not set to one.
#define NODE_BITS(p)
Get the control bits of a node.
#define ALEPH_FLATTEN
[[gnu::flatten]], or nothing where it would only make the compilation slower.
@ Spanning_Tree
Definition aleph-graph.H:79
Main namespace for Aleph-w library functions.
and
Check uniqueness with explicit hash + equality functors.
void next_ne() noexcept(noexcept(std::declval< Aleph::const_iterator_t< HeadC > & >().next_ne()) and noexcept(std::declval< ZipIterator< TailC... > & >().next_ne()))
Advance all underlying iterators (unchecked variant).
Definition ah-zip.H:252
GT::Node * next_target(const GT &tree, const GT &g) noexcept(noexcept(it.next_ne()))
void next_arc() noexcept(noexcept(it.next_ne()))
Frame(typename GT::Node *gnode, typename GT::Node *image, SA &sa)
Filtered iterator of adjacent arcs of a node.
Definition tpl_graph.H:1155
Stack of the frames of a depth-first search that does not recurse.
Generic graph and digraph implementations.
Utility algorithms and operations for graphs.