Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
Bidirectional_BFS.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
83# ifndef BIDIRECTIONAL_BFS_H
84# define BIDIRECTIONAL_BFS_H
85
86# include <ah-graph-concepts.H>
87
88# include <limits>
89# include <optional>
90# include <type_traits>
91# include <utility>
92# include <tpl_dynListQueue.H>
93# include <tpl_graph_utils.H>
94# include <ah-errors.H>
95
96namespace Aleph
97{
98
99namespace bidirectional_bfs_detail
100{
102 template <template <typename, class> class Itor>
103 struct is_in_iterator : std::false_type {};
104
107 template <>
108 struct is_in_iterator<In_Iterator> : std::true_type {};
109} // namespace bidirectional_bfs_detail
110
140template <AlephGraph GT,
141 template <typename, class> class Fwd_Itor = Node_Arc_Iterator,
142 template <typename, class> class Bck_Itor = Node_Arc_Iterator,
145{
146public:
147 using Node = typename GT::Node;
148 using Arc = typename GT::Arc;
149
150private:
151 SA sa;
152
153 // Whether the backward search goes with In_Iterator: on a digraph type,
154 // and on a graph of an undirected type that says that it is directed,
155 // whose list of a node holds only the arcs that leave it, it takes then
156 // the arcs into each node from an In_Arcs_Index
157 static constexpr bool backward_by_index =
159
160 // The arcs into each node, for a backward search by an index; nothing
161 // for another one
162 struct No_Index {};
164 std::conditional_t<backward_by_index, std::optional<In_Arcs_Index<GT, SA>>, No_Index>;
165
166 // Direction constants
167 static constexpr int UNSEEN = 0;
168 static constexpr int FORWARD = 1;
169 static constexpr int BACKWARD = 2;
170 static constexpr size_t INF_DIST = std::numeric_limits<size_t>::max();
171
172 struct BFS_Info
173 {
174 Node * fwd_parent = nullptr;
175 Node * bck_parent = nullptr;
176 Arc * fwd_parent_arc = nullptr;
177 Arc * bck_parent_arc = nullptr;
180 int dir = UNSEEN;
181 };
182
183#define BIBFS_INFO(p) (static_cast<BFS_Info *>(NODE_COOKIE(p)))
184#define BIBFS_DIR(p) (BIBFS_INFO(p)->dir)
185#define BIBFS_FWD_PARENT(p) (BIBFS_INFO(p)->fwd_parent)
186#define BIBFS_BCK_PARENT(p) (BIBFS_INFO(p)->bck_parent)
187#define BIBFS_FWD_PARC(p) (BIBFS_INFO(p)->fwd_parent_arc)
188#define BIBFS_BCK_PARC(p) (BIBFS_INFO(p)->bck_parent_arc)
189#define BIBFS_FWD_DIST(p) (BIBFS_INFO(p)->fwd_dist)
190#define BIBFS_BCK_DIST(p) (BIBFS_INFO(p)->bck_dist)
191
194 {
196 const GT * g = nullptr;
197
198 public:
203 BiBFS_Init_Guard(Bidirectional_BFS & __owner, const GT & __g) noexcept
204 : owner(&__owner), g(&__g)
205 {
206 // empty
207 }
208
217
220 {
221 owner->cleanup(*g);
222 }
223 };
224
225 void init(const GT & g)
226 {
227 for (typename GT::Node_Iterator it(g); it.has_curr(); it.next())
228 NODE_COOKIE(it.get_curr()) = nullptr;
229
230 try
231 {
232 for (typename GT::Node_Iterator it(g); it.has_curr(); it.next())
233 {
234 auto p = it.get_curr();
235 NODE_COOKIE(p) = new BFS_Info;
236 }
237 }
238 catch (...)
239 {
240 cleanup(g);
241 throw;
242 }
243 }
244
245 void cleanup(const GT & g)
246 {
247 for (typename GT::Node_Iterator it(g); it.has_curr(); it.next())
248 {
249 auto p = it.get_curr();
250 delete BIBFS_INFO(p);
251 NODE_COOKIE(p) = nullptr;
252 }
253 }
254
255 [[nodiscard]] bool is_seen(Node * p, const int dir) const noexcept
256 {
257 return (BIBFS_DIR(p) & dir) != 0;
258 }
259
260 void mark_seen(Node * p, const int dir) noexcept
261 {
262 BIBFS_DIR(p) |= dir;
263 }
264
265 [[nodiscard]] size_t get_dist(Node * p, const int dir) const noexcept
266 {
267 return dir == FORWARD ? BIBFS_FWD_DIST(p) : BIBFS_BCK_DIST(p);
268 }
269
270 void set_dist(Node * p, const int dir, const size_t d) noexcept
271 {
272 if (dir == FORWARD)
273 BIBFS_FWD_DIST(p) = d;
274 else
275 BIBFS_BCK_DIST(p) = d;
276 }
277
278 Node *& parent_ref(Node * p, const int dir) noexcept
279 {
280 if (dir == FORWARD)
281 return BIBFS_FWD_PARENT(p);
282 return BIBFS_BCK_PARENT(p);
283 }
284
285 Arc *& parent_arc_ref(Node * p, const int dir) noexcept
286 {
287 if (dir == FORWARD)
288 return BIBFS_FWD_PARC(p);
289 return BIBFS_BCK_PARC(p);
290 }
291
292 // The arc of curr to tgt, seen backward: tgt joins the next frontier
293 // if the backward search had not seen it, and is a meeting point if
294 // the forward one had; as the body of the loop of expand_frontier()
295 void visit_backward(Node * curr, const size_t curr_dist, Arc * arc, Node * tgt,
296 DynListQueue<Node *> & next_frontier,
297 size_t & best_len, Node *& best_meeting)
298 {
299 constexpr int my_dir = BACKWARD;
300 constexpr int other_dir = FORWARD;
301
302 const bool seen_my = is_seen(tgt, my_dir);
303 if (not seen_my)
304 {
305 mark_seen(tgt, my_dir);
306 parent_ref(tgt, my_dir) = curr;
307 parent_arc_ref(tgt, my_dir) = arc;
308 set_dist(tgt, my_dir, curr_dist + 1);
309 next_frontier.put(tgt);
310 }
311
312 if (is_seen(tgt, other_dir))
313 {
314 const auto my_dist = get_dist(tgt, my_dir);
315 const auto other_dist = get_dist(tgt, other_dir);
316
317 if (my_dist != INF_DIST and other_dist != INF_DIST)
318 {
319 const auto candidate_len = my_dist + other_dist;
320 if (candidate_len < best_len)
321 {
322 best_len = candidate_len;
323 best_meeting = tgt;
324 }
325 }
326 }
327 }
328
329 template <template <typename, class> class Itor>
330 void expand_frontier(const GT & g, DynListQueue<Node *> & frontier,
331 const int my_dir, const int other_dir,
332 size_t & best_len, Node *& best_meeting)
333 {
334 DynListQueue<Node *> next_frontier;
335
336 while (not frontier.is_empty())
337 {
338 auto curr = frontier.get();
339 const auto curr_dist = get_dist(curr, my_dir);
340
341 for (Itor<GT, SA> it(curr, sa); it.has_curr(); it.next())
342 {
343 auto arc = it.get_current_arc();
344 auto tgt = g.get_connected_node(arc, curr);
345
346 const bool seen_my = is_seen(tgt, my_dir);
347 if (not seen_my)
348 {
349 mark_seen(tgt, my_dir);
350 parent_ref(tgt, my_dir) = curr;
351 parent_arc_ref(tgt, my_dir) = arc;
352 set_dist(tgt, my_dir, curr_dist + 1);
353 next_frontier.put(tgt);
354 }
355
356 if (is_seen(tgt, other_dir))
357 {
358 const auto my_dist = get_dist(tgt, my_dir);
359 const auto other_dist = get_dist(tgt, other_dir);
360
361 if (my_dist != INF_DIST and other_dist != INF_DIST)
362 {
363 const auto candidate_len = my_dist + other_dist;
364 if (candidate_len < best_len)
365 {
366 best_len = candidate_len;
367 best_meeting = tgt;
368 }
369 }
370 }
371 }
372 }
373
374 frontier.swap(next_frontier);
375 }
376
377 // The backward step with In_Iterator on a digraph type, which keeps
378 // each arc only in the list of its source: it takes the arcs into each
379 // node from index, which the first step builds
380 void expand_backward(const GT & g, DynListQueue<Node *> & frontier,
381 size_t & best_len, Node *& best_meeting, Backward_Index & index)
382 {
383 if (not index)
384 index.emplace(g, sa);
385
386 DynListQueue<Node *> next_frontier;
387
388 while (not frontier.is_empty())
389 {
390 auto curr = frontier.get();
391 const auto curr_dist = get_dist(curr, BACKWARD);
392
393 for (auto it = index->get_it(curr); it.has_curr(); it.next_ne())
394 {
395 auto arc = it.get_curr_ne();
396 visit_backward(curr, curr_dist, arc, g.get_connected_node(arc, curr),
397 next_frontier, best_len, best_meeting);
398 }
399 }
400
401 frontier.swap(next_frontier);
402 }
403
404 void build_path(const GT & g, Node * start, Node * meeting, Node * end,
405 Path<GT> & path)
406 {
407 path.empty();
408
409 if (start == end)
410 {
411 path.set_graph(g, start);
412 return;
413 }
414
415 path.set_graph(g, start);
416
417 // Reconstruct start -> meeting using stored forward parent arcs.
418 DynList<Arc *> fwd_arcs;
419 for (auto curr = meeting; curr != start; curr = BIBFS_FWD_PARENT(curr))
420 {
421 ah_runtime_error_if(BIBFS_FWD_PARENT(curr) == nullptr)
422 << "Bidirectional_BFS: inconsistent forward parent chain";
423 ah_runtime_error_if(BIBFS_FWD_PARC(curr) == nullptr)
424 << "Bidirectional_BFS: missing forward parent arc";
425 fwd_arcs.insert(BIBFS_FWD_PARC(curr)); // prepend for start->meeting order
426 }
427
428 for (auto it = fwd_arcs.get_it(); it.has_curr(); it.next())
429 path.append(it.get_curr());
430
431 // Reconstruct meeting -> end using stored backward parent arcs.
432 for (auto curr = meeting; curr != end; curr = BIBFS_BCK_PARENT(curr))
433 {
434 ah_runtime_error_if(BIBFS_BCK_PARENT(curr) == nullptr)
435 << "Bidirectional_BFS: inconsistent backward parent chain";
436 ah_runtime_error_if(BIBFS_BCK_PARC(curr) == nullptr)
437 << "Bidirectional_BFS: missing backward parent arc";
438 path.append(BIBFS_BCK_PARC(curr));
439 }
440 }
441
442public:
447 Bidirectional_BFS(SA && __sa = SA()) : sa(std::move(__sa)) {}
448
453 Bidirectional_BFS(const SA & __sa) : sa(__sa) {}
454
476 bool find_path(const GT & g, Node * start, Node * end, Path<GT> & path)
477 {
478 ah_domain_error_if(start == nullptr) << "start node cannot be null";
479 ah_domain_error_if(end == nullptr) << "end node cannot be null";
480 ah_domain_error_if(g.get_num_nodes() == 0) << "graph is empty";
481
482 path.empty();
483
484 if (start == end)
485 {
486 path.set_graph(g, start);
487 return true;
488 }
489
490 init(g);
491 BiBFS_Init_Guard guard(*this, g);
492
493 bool found = false;
494 Node * meeting = nullptr;
495
496 mark_seen(start, FORWARD);
497 mark_seen(end, BACKWARD);
498 set_dist(start, FORWARD, 0);
499 set_dist(end, BACKWARD, 0);
500
501 DynListQueue<Node *> fwd_frontier;
502 DynListQueue<Node *> bck_frontier;
503
504 fwd_frontier.put(start);
505 bck_frontier.put(end);
506
507 size_t fwd_depth = 0;
508 size_t bck_depth = 0;
509 size_t best_len = INF_DIST;
510
511 // On a digraph type, the arcs into each node for the backward steps
512 [[maybe_unused]] Backward_Index index;
513
514 while (not fwd_frontier.is_empty() and not bck_frontier.is_empty())
515 {
516 const bool expand_forward = fwd_frontier.size() <= bck_frontier.size();
517
518 if (expand_forward)
519 {
520 expand_frontier<Fwd_Itor>(g, fwd_frontier, FORWARD, BACKWARD,
521 best_len, meeting);
522 ++fwd_depth;
523 }
524 else
525 {
527 expand_backward(g, bck_frontier, best_len, meeting, index);
528 else if constexpr (backward_by_index)
529 {
530 if (g.is_digraph())
531 expand_backward(g, bck_frontier, best_len, meeting, index);
532 else
533 expand_frontier<Bck_Itor>(g, bck_frontier, BACKWARD, FORWARD,
534 best_len, meeting);
535 }
536 else
537 expand_frontier<Bck_Itor>(g, bck_frontier, BACKWARD, FORWARD,
538 best_len, meeting);
539 ++bck_depth;
540 }
541
542 if (meeting != nullptr)
543 {
544 const size_t min_depth = fwd_depth < bck_depth ? fwd_depth : bck_depth;
545 const size_t lower_bound = min_depth + 1;
546 if (lower_bound >= best_len)
547 break;
548 }
549 }
550
551 found = meeting != nullptr;
552 if (found)
553 build_path(g, start, meeting, end, path);
554
555 return found;
556 }
557
566 bool operator()(const GT & g, Node * start, Node * end, Path<GT> & path)
567 {
568 return find_path(g, start, end, path);
569 }
570
578 Path<GT> operator()(const GT & g, Node * start, Node * end)
579 {
580 Path<GT> path(g);
581 find_path(g, start, end, path);
582 return path;
583 }
584
585#undef BIBFS_INFO
586#undef BIBFS_DIR
587#undef BIBFS_FWD_PARENT
588#undef BIBFS_BCK_PARENT
589#undef BIBFS_FWD_PARC
590#undef BIBFS_BCK_PARC
591#undef BIBFS_FWD_DIST
592#undef BIBFS_BCK_DIST
593};
594
595} // end namespace Aleph
596
597# endif // BIDIRECTIONAL_BFS_H
#define BIBFS_DIR(p)
#define BIBFS_FWD_DIST(p)
#define BIBFS_BCK_PARENT(p)
#define BIBFS_BCK_DIST(p)
#define BIBFS_FWD_PARENT(p)
#define BIBFS_INFO(p)
#define BIBFS_BCK_PARC(p)
#define BIBFS_FWD_PARC(p)
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_runtime_error_if(C)
Throws std::runtime_error if condition holds.
Definition ah-errors.H:415
C++20 concepts for the protocol shared by graph algorithms.
List_Graph< Graph_Node< Node_Info >, Graph_Arc< Arc_Info > > GT
RAII guard for BiBFS initialization and cleanup.
BiBFS_Init_Guard(const BiBFS_Init_Guard &)=delete
Deleted copy constructor.
BiBFS_Init_Guard & operator=(const BiBFS_Init_Guard &)=delete
Deleted copy assignment.
BiBFS_Init_Guard(BiBFS_Init_Guard &&)=delete
Deleted move constructor.
BiBFS_Init_Guard(Bidirectional_BFS &__owner, const GT &__g) noexcept
Constructor.
Bidirectional BFS for finding shortest unweighted paths.
Bidirectional_BFS(const SA &__sa)
Constructor with lvalue arc filter, const or not.
Path< GT > operator()(const GT &g, Node *start, Node *end)
Finds shortest path (operator interface returning path).
void build_path(const GT &g, Node *start, Node *meeting, Node *end, Path< GT > &path)
static constexpr bool backward_by_index
Node *& parent_ref(Node *p, const int dir) noexcept
Bidirectional_BFS(SA &&__sa=SA())
Constructor.
bool is_seen(Node *p, const int dir) const noexcept
static constexpr int UNSEEN
static constexpr int BACKWARD
void mark_seen(Node *p, const int dir) noexcept
void visit_backward(Node *curr, const size_t curr_dist, Arc *arc, Node *tgt, DynListQueue< Node * > &next_frontier, size_t &best_len, Node *&best_meeting)
std::conditional_t< backward_by_index, std::optional< In_Arcs_Index< GT, SA > >, No_Index > Backward_Index
void expand_frontier(const GT &g, DynListQueue< Node * > &frontier, const int my_dir, const int other_dir, size_t &best_len, Node *&best_meeting)
static constexpr size_t INF_DIST
static constexpr int FORWARD
bool find_path(const GT &g, Node *start, Node *end, Path< GT > &path)
Finds the shortest unweighted path between start and end.
Arc *& parent_arc_ref(Node *p, const int dir) noexcept
void set_dist(Node *p, const int dir, const size_t d) noexcept
void expand_backward(const GT &g, DynListQueue< Node * > &frontier, size_t &best_len, Node *&best_meeting, Backward_Index &index)
size_t get_dist(Node *p, const int dir) const noexcept
bool operator()(const GT &g, Node *start, Node *end, Path< GT > &path)
Finds shortest path (operator interface with path output).
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 swap(DynListQueue &__q) noexcept
Swap this with __q in constant time.
size_t size() const noexcept
Return the number of elements.
bool is_empty() const noexcept
Return true if this is empty.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & insert(const T &item)
Definition htlist.H:1308
Filtered iterator for incoming arcs of a node.
Definition tpl_graph.H:2045
Path on a graph.
Definition tpl_graph.H:3832
void empty()
Clean the path: all the nodes and arc are removed.
Definition tpl_graph.H:3999
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
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
Definition graph-dry.H:975
bool is_digraph() const noexcept
Return true if the graph this is directed.
Definition graph-dry.H:937
Node * get_connected_node(Arc *arc, Node *node) const noexcept
Return the adjacent node to node through arc.
Definition graph-dry.H:1058
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
Definition ah-dry.H:663
A graph usable by the graph algorithms.
An arc filter (SA) for graph GT.
A graph type built with the Digraph template.
#define NODE_COOKIE(p)
Return the node cookie
Main namespace for Aleph-w library functions.
Itor lower_bound(Itor beg, Itor end, const T &value)
Find lower bound in a sorted range.
Definition ahAlgo.H:1190
and
Check uniqueness with explicit hash + equality functors.
static std::atomic< bool > init
Definition hash-fct.C:54
STL namespace.
Default filter for filtered iterators on arcs.
Definition tpl_graph.H:1024
Filtered iterator of adjacent arcs of a node.
Definition tpl_graph.H:1155
Whether the iterator template is not In_Iterator.
Dynamic queue implementation based on linked lists.
Utility algorithms and operations for graphs.