Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
eulerian.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
94# ifndef EULERIAN_H
95# define EULERIAN_H
96
97# include <ah-graph-concepts.H>
98
99# include <tpl_graph.H>
100# include <tpl_graph_utils.H>
101
102namespace Aleph
103{
104
114{
115 Cycle,
116 Path,
117 None
118};
119
120namespace eulerian_detail
121{
128 template <class GT, class SA>
129 size_t degree(const GT & g, typename GT::Node * p, SA & sa)
130 {
131 size_t d = 0;
132 for (Node_Arc_Iterator<GT, SA> it(p, sa); it.has_curr(); it.next_ne())
133 d += (not g.is_digraph() and it.get_tgt_node_ne() == p) ? 2 : 1;
134 return d;
135 }
136
144 template <class GT, class SA>
145 bool arcs_are_together(const GT & g, SA & sa)
146 {
147 using Node = typename GT::Node;
148 for (Node_Iterator<GT> it(g); it.has_curr(); it.next_ne())
149 NODE_COOKIE(it.get_curr()) = it.get_curr();
150
151 auto root = [] (Node * x) noexcept
152 {
153 Node * r = x;
154 while (NODE_COOKIE(r) != r)
155 r = static_cast<Node *>(NODE_COOKIE(r));
156 while (x != r) // path compression
157 {
158 Node * next = static_cast<Node *>(NODE_COOKIE(x));
159 NODE_COOKIE(x) = r;
160 x = next;
161 }
162 return r;
163 };
164
165 for (Arc_Iterator<GT, SA> it(g, sa); it.has_curr(); it.next_ne())
166 {
167 Node * a = root(g.get_src_node(it.get_curr_ne()));
168 Node * b = root(g.get_tgt_node(it.get_curr_ne()));
169 if (a != b)
170 NODE_COOKIE(a) = b;
171 }
172
173 bool together = true;
174 Node * component = nullptr;
175 for (Arc_Iterator<GT, SA> it(g, sa); together and it.has_curr(); it.next_ne())
176 {
177 Node * r = root(g.get_src_node(it.get_curr_ne()));
178 if (component == nullptr)
179 component = r;
180 together = r == component;
181 }
182
184 return together;
185 }
186} // namespace eulerian_detail
187
237template <AlephGraph GT,
238 NodeFilter<GT> SN = Dft_Show_Node<GT>,
239 ArcFilter<GT> SA = Dft_Show_Arc<GT> >
241{
244
254 {
255 assert(not g.is_digraph());
256
257 size_t odd_degree_count = 0;
258 for (Node_Iterator<GT, SN> it(g, sn); it.has_curr(); it.next_ne())
259 odd_degree_count += eulerian_detail::degree(g, it.get_curr(), sa.get()) % 2;
260
261 if (odd_degree_count != 0 and odd_degree_count != 2)
262 return Eulerian_Type::None; // more than 2 odd degrees: not Eulerian
263
264 if (not eulerian_detail::arcs_are_together(g, sa.get()))
265 return Eulerian_Type::None;
266
267 return odd_degree_count == 0 ? Eulerian_Type::Cycle : Eulerian_Type::Path;
268 }
269
280 {
281 assert(g.is_digraph());
282
284
285 // First pass: count in-degrees using node counters
286 for (Arc_Iterator<GT, SA> it(g, sa); it.has_curr(); it.next_ne())
287 NODE_COUNTER(it.get_tgt_node_ne())++;
288
289 // Count imbalanced vertices
290 size_t start_vertices = 0; // out - in == 1
291 size_t end_vertices = 0; // in - out == 1
292 size_t imbalanced = 0; // |in - out| > 1
293
294 for (Node_Iterator<GT, SN> it(g, sn); it.has_curr(); it.next_ne())
295 {
296 typename GT::Node * p = it.get_curr();
297 const long out_deg = long(eulerian_detail::degree(g, p, sa.get()));
298 const long in_deg = NODE_COUNTER(p);
299 const long diff = out_deg - in_deg;
300
301 if (diff == 0)
302 continue; // Balanced vertex
303 else if (diff == 1)
304 ++start_vertices;
305 else if (diff == -1)
306 ++end_vertices;
307 else
308 ++imbalanced;
309 }
310
311 const bool cycle = start_vertices == 0 and end_vertices == 0;
312 if (imbalanced > 0 or not (cycle or (start_vertices == 1 and end_vertices == 1)))
313 return Eulerian_Type::None;
314
315 if (not eulerian_detail::arcs_are_together(g, sa.get()))
316 return Eulerian_Type::None;
317
319 }
320
321public:
322
329 Test_Eulerian(SN && __sn = SN(), SA && __sa = SA())
330 : sn(std::move(__sn)), sa(std::move(__sa))
331 {
332 // empty
333 }
334
353 {
354 if (g.is_digraph())
355 return analyze_digraph(g);
356 else
357 return analyze_graph(g);
358 }
359
372 bool operator () (GT & g)
373 {
374 return compute(g) == Eulerian_Type::Cycle;
375 }
376
389 {
390 auto result = compute(g);
391 return result == Eulerian_Type::Cycle || result == Eulerian_Type::Path;
392 }
393
407 {
408 if (g.is_digraph())
409 {
411 for (Arc_Iterator<GT, SA> it(g, sa); it.has_curr(); it.next_ne())
412 NODE_COUNTER(it.get_tgt_node_ne())++;
413
414 for (Node_Iterator<GT, SN> it(g, sn); it.has_curr(); it.next_ne())
415 {
416 typename GT::Node * p = it.get_curr();
417 if (long(eulerian_detail::degree(g, p, sa.get())) != NODE_COUNTER(p))
418 return false;
419 }
420 return true;
421 }
422 else
423 {
424 for (Node_Iterator<GT, SN> it(g, sn); it.has_curr(); it.next_ne())
425 if (eulerian_detail::degree(g, it.get_curr(), sa.get()) % 2 == 1)
426 return false;
427 return true;
428 }
429 }
430};
431
432
473template <AlephGraph GT,
474 NodeFilter<GT> SN = Dft_Show_Node<GT>,
475 ArcFilter<GT> SA = Dft_Show_Arc<GT> >
477{
480
492 {
493 typename GT::Node * start = nullptr;
494 typename GT::Node * odd_vertex = nullptr;
495
496 if (g.is_digraph())
497 {
498 // For digraphs, find vertex with out-degree > in-degree (start of path)
500 for (Arc_Iterator<GT, SA> it(g, sa); it.has_curr(); it.next_ne())
501 NODE_COUNTER(it.get_tgt_node_ne())++;
502
503 for (Node_Iterator<GT, SN> it(g, sn); it.has_curr(); it.next_ne())
504 {
505 typename GT::Node * p = it.get_curr();
506 const long out_deg = long(eulerian_detail::degree(g, p, sa.get()));
507 if (out_deg > 0)
508 {
509 if (start == nullptr)
510 start = p;
511 if (out_deg > NODE_COUNTER(p))
512 odd_vertex = p; // out > in: this is start of path
513 }
514 }
515 }
516 else
517 {
518 // For undirected, find vertex with odd degree
519 for (Node_Iterator<GT, SN> it(g, sn); it.has_curr(); it.next_ne())
520 {
521 typename GT::Node * p = it.get_curr();
522 const size_t deg = eulerian_detail::degree(g, p, sa.get());
523 if (deg > 0)
524 {
525 if (start == nullptr)
526 start = p;
527 if (deg % 2 == 1)
528 odd_vertex = p;
529 }
530 }
531 }
532
533 // For paths, must start at odd-degree vertex
534 if (type == Eulerian_Type::Path && odd_vertex != nullptr)
535 return odd_vertex;
536
537 return start;
538 }
539
548 {
549 // Mark all arcs as unused
550 g.reset_arcs();
551
553 DynList<typename GT::Arc*> current_path;
555
556 stack.insert(start);
557
558 while (not stack.is_empty())
559 {
560 typename GT::Node * curr = stack.get_first();
561
562 // Find an unused edge from curr
563 typename GT::Arc * unused_arc = nullptr;
564 for (Node_Arc_Iterator<GT, SA> it(curr, sa); it.has_curr(); it.next_ne())
565 {
566 typename GT::Arc * arc = it.get_curr();
567 if (not IS_ARC_VISITED(arc, Depth_First))
568 {
569 unused_arc = arc;
570 break;
571 }
572 }
573
574 if (unused_arc != nullptr)
575 {
576 // Mark arc as used
577 ARC_BITS(unused_arc).set_bit(Depth_First, true);
578
579 // Get the other endpoint
580 typename GT::Node * next = g.get_connected_node(unused_arc, curr);
581
582 stack.insert(next);
583 current_path.insert(unused_arc);
584 }
585 else
586 {
587 // No unused edges from curr - backtrack
588 stack.remove_first();
589 if (not current_path.is_empty())
590 result.insert(current_path.remove_first());
591 }
592 }
593
594 // Each arc went to the front of result when its walk backtracked past
595 // it, the last of the walk first, so that result is in order
596 return result;
597 }
598
607 {
608 // Mark all arcs as unused
609 g.reset_arcs();
610
612 DynList<typename GT::Arc*> current_path;
614
615 stack.insert(start);
616
617 while (not stack.is_empty())
618 {
619 typename GT::Node * curr = stack.get_first();
620
621 // Find an unused outgoing edge from curr
622 typename GT::Arc * unused_arc = nullptr;
623 for (Node_Arc_Iterator<GT, SA> it(curr, sa); it.has_curr(); it.next_ne())
624 {
625 typename GT::Arc * arc = it.get_curr();
626 if (not IS_ARC_VISITED(arc, Depth_First))
627 {
628 unused_arc = arc;
629 break;
630 }
631 }
632
633 if (unused_arc != nullptr)
634 {
635 // Mark arc as used
636 ARC_BITS(unused_arc).set_bit(Depth_First, true);
637
638 // Get target node
639 typename GT::Node * next = g.get_tgt_node(unused_arc);
640
641 stack.insert(next);
642 current_path.insert(unused_arc);
643 }
644 else
645 {
646 // No unused edges from curr - backtrack
647 stack.remove_first();
648 if (not current_path.is_empty())
649 result.insert(current_path.remove_first());
650 }
651 }
652
653 // Each arc went to the front of result when its walk backtracked past
654 // it, the last of the walk first, so that result is in order
655 return result;
656 }
657
658public:
659
666 Find_Eulerian_Path(SN && __sn = SN(), SA && __sa = SA())
667 : sn(std::move(__sn)), sa(std::move(__sa))
668 {
669 // empty
670 }
671
680
701 {
702 Result result;
703
704 // First check if Eulerian path/cycle exists
705 Test_Eulerian<GT, SN, SA> tester(SN(sn.get()), SA(sa.get())); // copies
706 result.type = tester.compute(g);
707
708 if (result.type == Eulerian_Type::None)
709 return result;
710
711 // Find starting vertex. There is none only if no arc is shown: then
712 // the empty walk is the Eulerian cycle, as Test_Eulerian says
713 typename GT::Node * start = find_start_vertex(g, result.type);
714
715 if (start == nullptr)
716 return result;
717
718 // Run Hierholzer's algorithm
719 if (g.is_digraph())
720 result.path = hierholzer_directed(g, start);
721 else
722 result.path = hierholzer_undirected(g, start);
723
724 return result;
725 }
726
734 {
735 return (*this)(g).path;
736 }
737
745 {
746 Result result = (*this)(g);
748
749 if (result.type == Eulerian_Type::None || result.path.is_empty())
750 return nodes;
751
752 // Get first node
753 typename GT::Arc * first_arc = result.path.get_first();
754 typename GT::Node * curr;
755
756 if (g.is_digraph())
757 curr = g.get_src_node(first_arc);
758 else
759 {
760 // For undirected, need to find proper starting node
761 typename GT::Node * start = find_start_vertex(g, result.type);
762 curr = start;
763 }
764
765 nodes.append(curr);
766
767 for (auto arc : result.path)
768 {
769 if (g.is_digraph())
770 curr = g.get_tgt_node(arc);
771 else
772 curr = g.get_connected_node(arc, curr);
773 nodes.append(curr);
774 }
775
776 return nodes;
777 }
778};
779
780} // end namespace Aleph
781
782# endif // EULERIAN_H
C++20 concepts for the protocol shared by graph algorithms.
WeightedDigraph::Node Node
List_Graph< Graph_Node< Node_Info >, Graph_Arc< Arc_Info > > GT
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 & insert(const T &item)
Definition htlist.H:1308
T remove_first()
See remove().
Definition htlist.H:1473
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
Finds and constructs an Eulerian path or cycle using Hierholzer's algorithm.
Definition eulerian.H:477
GT::Node * find_start_vertex(GT &g, Eulerian_Type type)
Find starting vertex for Eulerian path/cycle.
Definition eulerian.H:491
Kept_Filter< SA > sa
Definition eulerian.H:479
DynList< typename GT::Node * > find_node_sequence(GT &g)
Get the node sequence of the Eulerian path/cycle.
Definition eulerian.H:744
DynList< typename GT::Arc * > find_path(GT &g)
Get only the arc list (convenience method).
Definition eulerian.H:733
DynList< typename GT::Arc * > hierholzer_undirected(GT &g, typename GT::Node *start)
Hierholzer's algorithm for undirected graphs.
Definition eulerian.H:547
Kept_Filter< SN > sn
Definition eulerian.H:478
DynList< typename GT::Arc * > hierholzer_directed(GT &g, typename GT::Node *start)
Hierholzer's algorithm for directed graphs.
Definition eulerian.H:606
Find_Eulerian_Path(SN &&__sn=SN(), SA &&__sa=SA())
Construct an Eulerian path finder with optional filters.
Definition eulerian.H:666
Result operator()(GT &g)
Find an Eulerian path or cycle in the graph.
Definition eulerian.H:700
constexpr bool is_empty() const noexcept
Definition htlist.H:434
A filter that an algorithm object keeps: one given as an lvalue is used where it is,...
Definition tpl_graph.H:1249
Filtered iterator on the nodes of a graph.
Definition tpl_graph.H:1287
Path on a graph.
Definition tpl_graph.H:3832
Tests whether a graph or digraph is Eulerian.
Definition eulerian.H:241
Eulerian_Type compute(GT &g)
Compute detailed Eulerian classification.
Definition eulerian.H:352
Kept_Filter< SA > sa
Definition eulerian.H:243
Kept_Filter< SN > sn
Definition eulerian.H:242
bool operator()(GT &g)
Test if a graph has an Eulerian cycle.
Definition eulerian.H:372
Eulerian_Type analyze_digraph(GT &g)
Analyze Eulerian properties of a directed graph.
Definition eulerian.H:279
Test_Eulerian(SN &&__sn=SN(), SA &&__sa=SA())
Construct an Eulerian tester with optional filters.
Definition eulerian.H:329
bool test_degree_only(GT &g)
Check only degree conditions (without connectivity check).
Definition eulerian.H:406
Eulerian_Type analyze_graph(GT &g)
Analyze Eulerian properties of an undirected graph.
Definition eulerian.H:253
bool has_eulerian_path(GT &g)
Test if a graph has an Eulerian path.
Definition eulerian.H:388
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
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Definition graph-dry.H:1017
bool is_digraph() const noexcept
Return true if the graph this is directed.
Definition graph-dry.H:937
void reset_cookie_nodes() const noexcept
Reset all the cookies to `nullptr for all the nodes of graph.
Definition graph-dry.H:1367
void reset_counter_nodes() const noexcept
Reset all the counters to zero for all the nodes of graph.
Definition graph-dry.H:1350
Node * get_connected_node(Arc *arc, Node *node) const noexcept
Return the adjacent node to node through arc.
Definition graph-dry.H:1058
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
__gmp_expr< T, __gmp_binary_expr< __gmp_expr< T, U >, unsigned long int, __gmp_root_function > > root(const __gmp_expr< T, U > &expr, unsigned long int l)
Definition gmpfrxx.h:4138
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
#define NODE_COUNTER(p)
Get the counter of a node.
#define ARC_BITS(p)
Return the control bits of arc p.
#define NODE_COOKIE(p)
Return the node cookie
#define IS_ARC_VISITED(p, bit)
Determine whether the bit field is or not set to one.
@ Depth_First
Definition aleph-graph.H:73
bool arcs_are_together(const GT &g, SA &sa)
Whether the arcs that sa shows are all in one component.
Definition eulerian.H:145
size_t degree(const GT &g, typename GT::Node *p, SA &sa)
Degree of a node as an Eulerian walk counts it.
Definition eulerian.H:129
Main namespace for Aleph-w library functions.
Eulerian_Type
Enumeration for Eulerian graph classification.
Definition eulerian.H:114
@ Cycle
Graph has an Eulerian cycle.
@ None
Graph is not Eulerian.
@ Path
Graph has an Eulerian path but not a cycle.
and
Check uniqueness with explicit hash + equality functors.
bool diff(const C1 &c1, const C2 &c2, Eq e=Eq())
Check if two containers differ.
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
STL namespace.
Filtered iterator on all the arcs of a graph.
Definition tpl_graph.H:1200
Default filter for filtered iterators on arcs.
Definition tpl_graph.H:1024
Default filter for the graph nodes.
Definition tpl_graph.H:1228
Result type: path and its classification.
Definition eulerian.H:676
Eulerian_Type type
Classification (Cycle, Path, or None)
Definition eulerian.H:678
DynList< typename GT::Arc * > path
The Eulerian path/cycle as arc list.
Definition eulerian.H:677
Filtered iterator of adjacent arcs of a node.
Definition tpl_graph.H:1155
Represents a missing value.
Gsl_Compatible_Rng r
Generic graph and digraph implementations.
Utility algorithms and operations for graphs.