Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_find_path.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_FIND_PATH_H
53# define TPL_FIND_PATH_H
54
55# include <ah-graph-concepts.H>
56
57# include <tpl_dynListStack.H>
58# include <tpl_dynListQueue.H>
59# include <tpl_dfs_stack.H>
60# include <tpl_graph_utils.H>
61# include <ah-errors.H>
62
63namespace Aleph
64{
65 template <class GT>
67 {
68 bool operator ()(typename GT::Node *) const noexcept { return false; }
69 };
70
94 template <AlephGraph GT,
95 template <class, class> class Itor = Node_Arc_Iterator,
96 ArcFilter<GT> SA = Dft_Show_Arc<GT>>
98 {
100 GT *g_ptr = nullptr;
101
102 // A node of the path that waits for the one that it visits, and the
103 // next arc of it to look at
104 struct Frame
105 {
106 typename GT::Node *curr;
107 Itor<GT, SA> it;
108
109 [[gnu::always_inline]] ALEPH_FLATTEN
110 Frame(typename GT::Node *p, SA &sa) : curr(p), it(p, sa) {}
111
112 // next() and not next_ne(), so that what the filter throws goes on
113 [[gnu::always_inline]] ALEPH_FLATTEN void next_arc() { it.next(); }
114 };
115
116 // Takes the last node out of path; inlined, with what it calls, in the
117 // loop of find_path()
118 [[gnu::always_inline]] ALEPH_FLATTEN
119 static void remove_last_node(Path<GT> & path) { path.remove_last_node(); }
120
121 // Moves the iterator of f to the next arc not visited, which it
122 // marks, whose target is the goal or was not visited, and gives that
123 // target, with found telling whether it is the goal; nullptr when the
124 // arcs are done
125 template <class Op>
126 [[gnu::always_inline]]
127 typename GT::Node *next_target(Frame &f, Op &op, bool &found)
128 {
129 for (; f.it.has_curr(); f.next_arc())
130 {
131 auto next_arc = dfs_curr(f.it);
132 if (IS_ARC_VISITED(next_arc, Find_Path))
133 continue;
134
135 // the target before the mark, which the compiler takes for a
136 // store that could change the frame
137 auto next_node = g_ptr->get_connected_node(next_arc, f.curr);
138 ARC_BITS(next_arc).set_bit(Find_Path, true);
139 if (op(next_node)) // goal node reached?
140 {
141 found = true;
142 return next_node;
143 }
144
145 if (not IS_NODE_VISITED(next_node, Find_Path)) // there is no path from a visited one
146 return next_node;
147 }
148 return nullptr;
149 }
150
151 // Searches from curr, reached through arc, a node for which op() is
152 // true, and puts in path the path to it. A path can have as many nodes
153 // as the graph, too many for recursion, so that the search keeps its
154 // own stack; the order of the visits is that of a recursion.
155 template <class Op>
156 bool find_path(Dfs_Stack<Frame> & frames, typename GT::Node *curr,
157 typename GT::Arc *arc, Path<GT> & path, Op & op)
158 {
159 if (op(curr)) // goal node reached?
160 {
161 path.append(arc);
162 return true;
163 }
164
165 if (IS_NODE_VISITED(curr, Find_Path)) // has it been visited?
166 return false; // yes ==> there is no path from it
167
168 path.append(arc); // add curr_arc to the path
169 NODE_BITS(curr).set_bit(Find_Path, true);
170
171 // The node being visited keeps its iterator in here until it visits
172 // a node; then it waits in frames, where it goes on when it comes
173 // back. here is a Dfs_Here, which assigns the frames if their
174 // filter can be assigned: building them in place, in an optional,
175 // costs here up to 0.2 % with GCC
176 frames.clear();
177 auto here = dfs_here<Frame>(curr, sa);
178 bool found = false;
179 while (true)
180 {
181 if (auto next = next_target(dfs_frame(here), op, found))
182 { // the iterator stays on the arc to next, as in a recursion
183 path.append(dfs_curr(dfs_frame(here).it));
184 if (found)
185 return true;
186
187 NODE_BITS(next).set_bit(Find_Path, true);
188 frames.push(std::move(dfs_frame(here)));
189 dfs_replace(here, next, sa);
190 continue;
191 }
192
193 remove_last_node(path);
194 while (true) // back to the nodes that wait
195 {
196 if (frames.is_empty())
197 return false;
198
199 Frame & f = frames.top();
200 f.next_arc(); // past the arc to the node that was visited
201 if (auto next = next_target(f, op, found))
202 {
203 path.append(dfs_curr(f.it));
204 if (found)
205 return true;
206
207 NODE_BITS(next).set_bit(Find_Path, true);
208 dfs_replace(here, next, sa);
209 break;
210 }
211
212 remove_last_node(path);
213 frames.pop();
214 }
215 }
216 }
217
218 template <class Op>
219 bool find(const GT & g, typename GT::Node *start, Path<GT> & path, Op & op)
220 {
221 g_ptr = const_cast<GT *>(&g);
222 path.set_graph(g, start);
223
224 if (op(start))
225 return true;
226
229
230 NODE_BITS(start).set_bit(Find_Path, true);
231
232 // explore each of start's arcs
233 Dfs_Stack<Frame> frames;
234 for (Itor<GT, SA> i(start, sa); i.has_curr(); i.next())
235 {
236 auto arc = i.get_curr();
237 ARC_BITS(arc).set_bit(Find_Path, true);
238
239 auto next_node = g.get_connected_node(arc, start);
240 if (IS_NODE_VISITED(next_node, Find_Path))
241 continue;
242
243 if (find_path(frames, next_node, arc, path, op))
244 return true;
245 }
246
247 path.empty(); // there is no path
248
249 return false;
250 }
251
252 template <class Op>
253 bool find(const GT & g, typename GT::Node *start, Path<GT> & path, Op && op)
254 {
255 return find(g, start, path, op);
256 }
257
258 public:
259 Find_Path_Depth_First(SA && __sa = SA())
260 : sa(std::move(__sa))
261 { /* empty */
262 }
263
265 : sa(__sa)
266 { /* empty */
267 }
268
280 bool operator ()(const GT & g,
281 typename GT::Node *start, typename GT::Node *end,
282 Path<GT> & path)
283 {
284 return find(g, start, path, [end](auto p) { return p == end; });
285 }
286
297 typename GT::Node *start,
298 typename GT::Node *end)
299 {
300 Path<GT> ret(g);
301 find(g, start, ret, [end](auto p) { return p == end; });
302 return ret;
303 }
304
317 template <class Op>
318 Path<GT> operator ()(const GT & g, typename GT::Node *start, Op & op)
319 {
320 Path<GT> ret(g);
321 find<Op>(g, start, ret, op);
322 return ret;
323 }
324
325 template <class Op = Dft_Goal_Node<GT>>
326 Path<GT> operator ()(const GT & g, typename GT::Node *start, Op && op)
327 {
328 Path<GT> ret(g);
329 find<Op>(g, start, ret, op);
330 return ret;
331 }
332 };
333
334
359 template <AlephGraph GT,
360 template <typename, class> class Itor = Node_Arc_Iterator,
361 ArcFilter<GT> SA = Dft_Show_Arc<GT>>
363 {
365
366 template <class Op>
367 bool find_path(const GT & g, typename GT::Node *start,
368 Path<GT> & path, Op & op)
369 {
370 if (not path.inside_graph(g))
371 {
372 ah_invalid_argument_if(true) << "Path does not belong to graph";
373 }
374
375 path.empty(); // clear anything that may be in path
376 if (op(start)) // the path of no arc, as that of Find_Path_Depth_First
377 {
378 path.init(start);
379 return true;
380 }
381
382 g.reset_nodes();
383 g.reset_arcs();
384
386
387 for (Itor<GT, SA> i(start, sa); i.has_curr(); i.next())
388 q.put(i.get_current_arc());
389
390 NODE_BITS(start).set_bit(Find_Path, true); // mark it visited
391
392 typename GT::Node *end = nullptr;
393
394 while (not q.is_empty()) // while arcs remain to be visited
395 {
396 auto arc = q.get();
397 auto src = g.get_src_node(arc);
398 auto tgt = g.get_tgt_node(arc);
399
401 continue;
402
403 if (IS_NODE_VISITED(tgt, Find_Path))
404 std::swap(src, tgt);
405
406 ARC_BITS(arc).set_bit(Find_Path, true);
407 NODE_BITS(tgt).set_bit(Find_Path, true);
408 NODE_COOKIE(tgt) = arc; // the arc of the path to tgt
409
410 if (op(tgt)) // was a path satisfying op found?
411 {
412 end = tgt;
413 break;
414 }
415
416 for (Itor<GT, SA> i(tgt, sa); i.has_curr(); i.next())
417 {
418 auto a = i.get_current_arc();
419 if (IS_ARC_VISITED(a, Find_Path)) // arc visited?
420 continue; // yes ==> move on to the next one
421
422 // check the arc's nodes to see whether they were visited
425 continue; // nodes already visited ==> do not enqueue the arc
426
427 q.put(a);
428 }
429 }
430
431 if (not end)
432 return false;
433
434 q.empty();
435 // By the arcs of the search, not by the nodes, whose arcs between
436 // them may be others: hidden, or parallel, or the other way
437 path.insert(end);
438 for (auto p = end; p != start; p = path.get_first_node())
439 path.insert(static_cast<typename GT::Arc *>(NODE_COOKIE(p)));
440
441 return true;
442 }
443
444 template <class Op>
445 bool find_path(const GT & g, typename GT::Node *start,
446 Path<GT> & path, Op && op)
447 {
448 return find_path(g, start, path, op);
449 }
450
451 public:
453 : sa(_sa)
454 { /* Empty */
455 }
456
457 Find_Path_Breadth_First(SA && _sa = SA())
458 : sa(std::move(_sa))
459 { /* Empty */
460 }
461
471 template <class Op>
472 Path<GT> operator ()(const GT & g, typename GT::Node *start, Op & op)
473 {
474 Path<GT> ret(g);
475 find_path(g, start, ret, op);
476 return ret;
477 }
478
479 template <class Op>
480 Path<GT> operator ()(const GT & g, typename GT::Node *start, Op && op)
481 {
482 Path<GT> ret(g);
483 find_path(g, start, ret, op);
484 return ret;
485 }
486
497 bool operator ()(const GT & g, typename GT::Node *start,
498 typename GT::Node *end, Path<GT> & path)
499 {
500 return find_path(g, start, path, [end](auto p) { return p == end; });
501 }
502
513 typename GT::Node *start, typename GT::Node *end)
514 {
515 Path<GT> ret(g);
516 find_path(g, start, ret, [end](auto p) { return p == end; });
517 return ret;
518 }
519 };
520
530 template <AlephGraph GT,
531 template <typename, class> class Itor = Out_Iterator,
532 ArcFilter<GT> SA = Dft_Show_Arc<GT>>
534 {
535 const GT & g;
537
538 template <template <typename T> class Q, class Op>
539 Path<GT> find(typename GT::Node *start, Op & op)
540 {
541 if (op(start)) // the path of no arc, as that of Find_Path_Depth_First
542 return Path<GT>(g, start);
543
544 g.reset_nodes();
545 g.reset_arcs();
546
547 start->set_state(Processed);
548
549 Q<typename GT::Arc *> q;
550 for (Itor<GT, SA> it(start, sa); it.has_curr(); it.next())
551 {
552 auto a = it.get_curr();
553 auto tgt = g.get_tgt_node(a);
554 if (tgt == start) // a loop, which would make start a target
555 continue;
556 tgt->set_state(Processing);
557 a->set_state(Processing);
558 q.put(a);
559 }
560
561 typename GT::Node *end = nullptr, *curr = nullptr;
562 while (not q.is_empty())
563 {
564 auto arc = q.get();
565 assert(arc->state() == Processing);
566 arc->set_state(Processed);
567
568 curr = g.get_tgt_node(arc);
569 if (curr->state() == Processed)
570 continue;
571
572 curr->set_state(Processed);
573 NODE_COOKIE(curr) = arc; // the arc of the path to curr
574
575 if (op(curr))
576 {
577 end = curr;
578 break;
579 }
580
581 for (Itor<GT, SA> it(curr, sa); it.has_curr(); it.next())
582 {
583 auto a = it.get_curr();
585
586 auto tgt = g.get_tgt_node(a);
587 if (tgt->state() == Processed)
588 continue;
589
590 if (tgt->state() != Processed)
591 {
592 q.put(a);
593 tgt->set_state(Processing);
594 }
595 else
596 a->set_state(Processed);
597 }
598 } // end while
599
600 Path<GT> ret(g);
601 if (not end)
602 return ret;
603
604 assert(curr == end);
605
606 // By the arcs of the search, not by the nodes, whose arcs between
607 // them may be others: hidden, or parallel, or the other way
608 ret.init(end);
609 for (; curr != start; curr = ret.get_first_node())
610 ret.insert_directed(static_cast<typename GT::Arc *>(NODE_COOKIE(curr)));
611
612 return ret;
613 }
614
615 public:
616 Directed_Find_Path(const GT & __g, SA & __sa) : g(__g), sa(__sa) {}
617
618 Directed_Find_Path(const GT & __g, SA && __sa = SA())
619 : g(__g), sa(std::move(__sa)) {}
620
621 template <class Op>
622 Path<GT> dfs(typename GT::Node *start, Op & op)
623 {
624 return find<DynListStack, Op>(start, op);
625 }
626
627 template <class Op>
628 Path<GT> dfs(typename GT::Node *start, Op && op)
629 {
630 return find<DynListStack, Op>(start, op);
631 }
632
633 template <class Op>
634 Path<GT> bfs(typename GT::Node *start, Op & op)
635 {
636 return find<DynListQueue, Op>(start, op);
637 }
638
639 template <class Op>
640 Path<GT> bfs(typename GT::Node *start, Op && op)
641 {
642 return find<DynListQueue, Op>(start, op);
643 }
644
645 Path<GT> dfs(typename GT::Node *start, typename GT::Node *end)
646 {
647 return dfs(start, [end](auto p) { return p == end; });
648 }
649
650 Path<GT> bfs(typename GT::Node *start, typename GT::Node *end)
651 {
652 return bfs(start, [end](auto p) { return p == end; });
653 }
654 };
655} // namespace Aleph
656
657# endif // TPL_FIND_PATH_H
Exception handling system with formatted messages for Aleph-w.
#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.
List_Graph< Graph_Node< Node_Info >, Graph_Arc< Arc_Info > > GT
Stack of the frames of a depth-first search that does not recurse.
void clear() noexcept
Destroys all the frames, and keeps the room.
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.
Path search on directed graphs defined through a graph class (not a digraph).
Directed_Find_Path(const GT &__g, SA &__sa)
Path< GT > dfs(typename GT::Node *start, Op &&op)
Path< GT > dfs(typename GT::Node *start, Op &op)
Path< GT > bfs(typename GT::Node *start, typename GT::Node *end)
Path< GT > dfs(typename GT::Node *start, typename GT::Node *end)
Directed_Find_Path(const GT &__g, SA &&__sa=SA())
Path< GT > find(typename GT::Node *start, Op &op)
Path< GT > bfs(typename GT::Node *start, Op &&op)
Path< GT > bfs(typename GT::Node *start, Op &op)
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.
void empty() noexcept
Empty the queue.
bool is_empty() const noexcept
Return true if this is empty.
Performs a breadth-first search for a path between a pair of nodes.
Path< GT > operator()(const GT &g, typename GT::Node *start, Op &op)
Invokes the breadth-first path search.
bool find_path(const GT &g, typename GT::Node *start, Path< GT > &path, Op &&op)
bool find_path(const GT &g, typename GT::Node *start, Path< GT > &path, Op &op)
Performs a depth-first search for a path between a pair of nodes.
Find_Path_Depth_First(SA &&__sa=SA())
bool operator()(const GT &g, typename GT::Node *start, typename GT::Node *end, Path< GT > &path)
Invokes the depth-first path search.
bool find_path(Dfs_Stack< Frame > &frames, typename GT::Node *curr, typename GT::Arc *arc, Path< GT > &path, Op &op)
GT::Node * next_target(Frame &f, Op &op, bool &found)
static void remove_last_node(Path< GT > &path)
bool find(const GT &g, typename GT::Node *start, Path< GT > &path, Op &&op)
bool find(const GT &g, typename GT::Node *start, Path< GT > &path, Op &op)
A filter that an algorithm object keeps: one given as an lvalue is used where it is,...
Definition tpl_graph.H:1249
Filtered iterator for outcoming arcs of a node.
Definition tpl_graph.H:1942
Path on a graph.
Definition tpl_graph.H:3832
void insert(Arc *arc)
Insert an arc as the first of a path.
Definition tpl_graph.H:4195
void empty()
Clean the path: all the nodes and arc are removed.
Definition tpl_graph.H:3999
void init(Node *start_node)
Set the first node of a path.
Definition tpl_graph.H:3947
void insert_directed(Node *p)
Insert a node at the beginning of a directed path.
Definition tpl_graph.H:4266
Node * get_first_node() const
Return the first node of path; throws overflow_error if path is empty.
Definition tpl_graph.H:4316
bool inside_graph(const GT &gr) const noexcept
Return true if this is on graph gr
Definition tpl_graph.H:3927
void set_graph(const GT &__g, Node *start_node=nullptr)
Set the graph of the path.
Definition tpl_graph.H:3977
void append(Arc *arc)
Append an arc to the path.
Definition tpl_graph.H:4052
Node * remove_last_node()
Remove the last node of path.
Definition tpl_graph.H:4363
void set_state(unsigned int s) noexcept
Set the state to value s
Definition graph-dry.H:762
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
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_connected_node(Arc *arc, Node *node) const noexcept
Return the adjacent node to node through arc.
Definition graph-dry.H:1058
void reset_bit_arcs(int bit) const noexcept
Reset bit to zero for all the arcs of graph.
Definition graph-dry.H:1332
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
const unsigned char Processed
The node or arc has already been processed.
Definition aleph-graph.C:39
void dfs_replace(T &here, Args &&...args)
Replaces the frame that a Dfs_Here holds with one built with args, by assignment.
const unsigned char Processing
The node are being processed; probably it is inside a queue, stack or heap.
Definition aleph-graph.C:38
#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
decltype(auto) dfs_curr(const It &it)
The current item of an iterator that has one.
T & dfs_frame(T &here) noexcept
The frame that a Dfs_Here holds.
#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.
@ Find_Path
Definition aleph-graph.H:76
Main namespace for Aleph-w library functions.
and
Check uniqueness with explicit hash + equality functors.
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
STL namespace.
bool operator()(typename GT::Node *) const noexcept
Default filter for filtered iterators on arcs.
Definition tpl_graph.H:1024
Frame(typename GT::Node *p, 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.
Dynamic queue implementation based on linked lists.
Dynamic stack implementation based on linked lists.
Utility algorithms and operations for graphs.