Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
Zero_One_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 ZERO_ONE_BFS_H
84# define ZERO_ONE_BFS_H
85
86# include <ah-graph-concepts.H>
87
88# include <limits>
89# include <type_traits>
90# include <tpl_dynDlist.H>
91# include <tpl_graph_utils.H>
92# include <ah-errors.H>
93
94namespace Aleph
95{
96
127template <AlephGraph GT,
128 ArcDistance<GT> Distance = Dft_Dist<GT>,
129 template <typename, class> class Itor = Node_Arc_Iterator,
130 ArcFilter<GT> SA = Dft_Show_Arc<GT>>
132{
133public:
135 using Node = typename GT::Node;
136 using Arc = typename GT::Arc;
137
138private:
139 SA sa;
141 bool painted = false;
142 GT * ptr_g = nullptr;
143 Node * s = nullptr;
144
145 static constexpr Distance_Type Inf =
146 std::numeric_limits<Distance_Type>::max();
147
149 {
153
154 Node_Info() noexcept : dist(Inf), parent(nullptr), parent_arc(nullptr) {}
155 };
156
157 // The data of the nodes during a computation; none is kept after it
159
160#define ZOB_INFO(p) (static_cast<Node_Info *>(NODE_COOKIE(p)))
161#define ZOB_DIST(p) (ZOB_INFO(p)->dist)
162#define ZOB_PARENT(p) (ZOB_INFO(p)->parent)
163#define ZOB_PARENT_ARC(p) (ZOB_INFO(p)->parent_arc)
164
166 {
167 for (auto it = owned_node_infos.get_it(); it.has_curr(); it.next())
168 {
169 auto item = it.get_curr();
170 auto p = item.first;
171 auto info = item.second;
172 if (info != nullptr)
173 delete info;
174 if (NODE_COOKIE(p) == info)
175 NODE_COOKIE(p) = nullptr;
176 }
177 owned_node_infos.empty();
178 }
179
181 {
182 painted = false;
183 ptr_g = nullptr;
184 s = nullptr;
185 }
186
189 {
190 Zero_One_BFS * owner = nullptr;
191 const GT * g = nullptr;
192 bool committed = false;
193
194 public:
199 ZOB_Init_Guard(Zero_One_BFS & __owner, const GT & __g) noexcept
200 : owner(&__owner), g(&__g)
201 {
202 // empty
203 }
204
213
215 void commit() noexcept { committed = true; }
216
219 {
220 if (not committed)
221 {
224 }
225 }
226 };
227
228 void init(const GT & g)
229 {
230 ptr_g = &const_cast<GT &>(g);
232 for (typename GT::Node_Iterator it(g); it.has_curr(); it.next())
233 {
234 auto p = it.get_curr();
236 NODE_COOKIE(p) = nullptr;
237 }
238 for (typename GT::Arc_Iterator it(g); it.has_curr(); it.next())
239 g.reset_bit(it.get_curr(), Aleph::Spanning_Tree);
240
241 try
242 {
243 for (typename GT::Node_Iterator it(g); it.has_curr(); it.next())
244 {
245 auto p = it.get_curr();
246 auto info = new Node_Info;
247 NODE_COOKIE(p) = info;
248 try
249 {
250 owned_node_infos.append({p, info});
251 }
252 catch (...)
253 {
254 delete info;
255 NODE_COOKIE(p) = nullptr;
256 throw;
257 }
258 }
259 }
260 catch (...)
261 {
263 throw;
264 }
265 }
266
267 // Leaves the painting in the graph, as Dijkstra_Min_Paths does: the
268 // cookie of each node is its parent in the tree, and its counter, its
269 // distance from the start, a count of arcs of weight 1. The data of the
270 // computation goes.
271 void uninit_paint() noexcept
272 {
273 for (auto it = owned_node_infos.get_it(); it.has_curr(); it.next_ne())
274 {
275 auto [p, info] = it.get_curr();
276 NODE_COOKIE(p) = info->parent;
277 NODE_COUNTER(p) = info->dist == Inf ? 0 : static_cast<long>(info->dist);
278 delete info;
279 }
280 owned_node_infos.empty();
281 }
282
284 {
285 if (ptr_g == nullptr)
286 return;
287
289
290 for (typename GT::Node_Iterator it(*ptr_g); it.has_curr(); it.next())
291 {
292 auto p = it.get_curr();
294 }
295
296 for (typename GT::Arc_Iterator it(*ptr_g); it.has_curr(); it.next())
297 ptr_g->reset_bit(it.get_curr(), Aleph::Spanning_Tree);
298 }
299
300 void run_bfs(const GT & g, Node * start, Node * end = nullptr)
301 {
302 ZOB_DIST(start) = 0;
303 NODE_BITS(start).set_bit(Aleph::Spanning_Tree, true);
304
306 deque.append(start);
307
308 while (not deque.is_empty())
309 {
310 auto curr = deque.remove_first();
311 auto curr_dist = ZOB_DIST(curr);
312
313 if (end != nullptr and curr == end)
314 break;
315
316 for (Itor<GT, SA> it(curr, sa); it.has_curr(); it.next())
317 {
318 auto arc = it.get_current_arc();
319 auto tgt = g.get_connected_node(arc, curr);
320
321 auto w = distance(arc);
323 << "Zero_One_BFS: arc weight must be 0 or 1, got " << w;
324
325 auto new_dist = curr_dist + w;
326
327 if (new_dist < ZOB_DIST(tgt))
328 {
329 auto prev_parent_arc = ZOB_PARENT_ARC(tgt);
330 if (prev_parent_arc != nullptr)
331 ARC_BITS(prev_parent_arc).set_bit(Aleph::Spanning_Tree, false);
332
333 ZOB_DIST(tgt) = new_dist;
334 ZOB_PARENT(tgt) = curr;
335 ZOB_PARENT_ARC(tgt) = arc;
336 NODE_BITS(tgt).set_bit(Aleph::Spanning_Tree, true);
337
338 // Mark the selected parent arc in the spanning tree
339 ARC_BITS(arc).set_bit(Aleph::Spanning_Tree, true);
340
341 if (w == Distance_Type(0))
342 deque.insert(tgt); // push front
343 else
344 deque.append(tgt); // push back
345 }
346 }
347 }
348 }
349
350public:
356 Zero_One_BFS(Distance dist = Distance(), SA __sa = SA())
357 : sa(__sa), distance(dist)
358 {
359 // empty
360 }
361
368 ~Zero_One_BFS() noexcept
369 {
370 for (auto it = owned_node_infos.get_it(); it.has_curr(); it.next_ne())
371 delete it.get_curr().second;
372 }
373
377 [[nodiscard]] bool is_painted() const noexcept { return painted; }
378
382 [[nodiscard]] Node * get_start_node() const noexcept { return s; }
383
387 [[nodiscard]] GT * get_graph() const noexcept { return ptr_g; }
388
404 void paint_min_paths_tree(const GT & g, Node * start)
405 {
406 ah_domain_error_if(start == nullptr) << "start node cannot be null";
407 ah_domain_error_if(g.get_num_nodes() == 0) << "graph is empty";
408
409 // init() resets the painting of g; another graph, painted before,
410 // keeps its own
411 painted = false;
412 s = nullptr;
413
414 init(g);
415 ZOB_Init_Guard guard(*this, g);
416 s = start;
417 run_bfs(g, start);
418 uninit_paint();
419 guard.commit();
420 painted = true;
421 }
422
432 [[nodiscard]] Distance_Type get_distance(Node * node)
433 {
434 ah_domain_error_if(not painted) << "Graph has not been painted";
435 ah_domain_error_if(node == nullptr) << "node cannot be null";
436
437 if (node == s)
438 return Distance_Type(0);
439
441 << "node is not reachable from start";
442
443 // The painting keeps it in the counter, a count of arcs of weight 1
444 return static_cast<Distance_Type>(NODE_COUNTER(node));
445 }
446
457 {
458 ah_domain_error_if(not painted) << "Graph has not been painted";
459 ah_domain_error_if(ptr_g == nullptr) << "No computation has been done";
460 ah_domain_error_if(end == nullptr) << "end pointer is null";
461
462 path.empty();
463 if (end == s)
464 {
465 path.set_graph(*ptr_g, s);
466 return 0;
467 }
468
470 return Inf;
471
472 Distance_Type total = 0;
473 path.set_graph(*ptr_g, s);
475 for (auto curr = end; curr != s;)
476 {
477 auto parent = static_cast<Node *>(NODE_COOKIE(curr));
478 if (parent == nullptr)
479 return Inf;
480
481 bool found = false;
482 for (Itor<GT, SA> it(parent, sa); it.has_curr(); it.next())
483 {
484 auto arc = it.get_current_arc();
485 if (ptr_g->get_connected_node(arc, parent) == curr and
487 {
488 arcs.insert(arc);
489 total += distance(arc);
490 curr = parent;
491 found = true;
492 break;
493 }
494 }
495 if (not found)
496 return Inf;
497 }
498
499 for (auto it = arcs.get_it(); it.has_curr(); it.next())
500 path.append(it.get_curr());
501
502 return total;
503 }
504
522 Distance_Type find_min_path(const GT & g, Node * start, Node * end,
523 Path<GT> & path)
524 {
525 ah_domain_error_if(start == nullptr) << "start node cannot be null";
526 ah_domain_error_if(end == nullptr) << "end node cannot be null";
527 ah_domain_error_if(g.get_num_nodes() == 0) << "graph is empty";
528
529 path.empty();
530
531 // init() resets the painting of g; another graph, painted before,
532 // keeps its own
533 painted = false;
534 s = nullptr;
535
536 init(g);
537 ZOB_Init_Guard guard(*this, g);
538 s = start;
539 run_bfs(g, start, end);
540 uninit_paint();
541 guard.commit();
542 painted = true;
543
545 return Inf;
546
547 return get_min_path(end, path);
548 }
549
558 Distance_Type operator()(const GT & g, Node * start, Node * end,
559 Path<GT> & path)
560 {
561 return find_min_path(g, start, end, path);
562 }
563
564#undef ZOB_INFO
565#undef ZOB_DIST
566#undef ZOB_PARENT
567#undef ZOB_PARENT_ARC
568};
569
570} // end namespace Aleph
571
572# endif // ZERO_ONE_BFS_H
#define ZOB_PARENT_ARC(p)
#define ZOB_PARENT(p)
#define ZOB_DIST(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
C++20 concepts for the protocol shared by graph algorithms.
List_Graph< Graph_Node< Node_Info >, Graph_Arc< Arc_Info > > GT
long double w
Definition btreepic.C:153
Default distance accessor for arc weights.
Dynamic doubly linked list with O(1) size and bidirectional access.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & insert(const T &item)
Definition htlist.H:1308
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
RAII guard for Zero_One_BFS initialization and cleanup.
ZOB_Init_Guard(const ZOB_Init_Guard &)=delete
Deleted copy constructor.
void commit() noexcept
Commits the operation, preventing cleanup on destruction.
ZOB_Init_Guard & operator=(const ZOB_Init_Guard &)=delete
Deleted copy assignment.
~ZOB_Init_Guard() noexcept
Destructor.
ZOB_Init_Guard(ZOB_Init_Guard &&)=delete
Deleted move constructor.
ZOB_Init_Guard(Zero_One_BFS &__owner, const GT &__g) noexcept
Constructor.
0-1 BFS algorithm for shortest paths in graphs with 0/1 weights.
void init(const GT &g)
~Zero_One_BFS() noexcept
Destructor.
bool is_painted() const noexcept
Check if a computation has been performed.
void release_owned_node_infos() noexcept
static constexpr Distance_Type Inf
void uninit_paint() noexcept
GT * get_graph() const noexcept
Get the graph of the last computation.
Distance_Type operator()(const GT &g, Node *start, Node *end, Path< GT > &path)
Computes shortest path (operator interface).
Distance_Type get_min_path(Node *end, Path< GT > &path)
Extracts a shortest path from a previously painted graph.
void run_bfs(const GT &g, Node *start, Node *end=nullptr)
typename Distance::Distance_Type Distance_Type
DynList< std::pair< Node *, Node_Info * > > owned_node_infos
Zero_One_BFS(Distance dist=Distance(), SA __sa=SA())
Constructor.
Distance_Type find_min_path(const GT &g, Node *start, Node *end, Path< GT > &path)
Computes the shortest path from start to end.
typename GT::Node Node
void reset_state_after_failure() noexcept
void paint_min_paths_tree(const GT &g, Node *start)
Paints the shortest paths tree on the graph from start.
Distance_Type get_distance(Node *node)
Gets the accumulated distance to a node after painting.
Node * get_start_node() const noexcept
Get the start node of the last computation.
typename GT::Arc Arc
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
Definition graph-dry.H:975
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(Node *node, int bit) const noexcept
Reset the bit of node (to zero)
Definition graph-dry.H:1087
Definition deque.H:48
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
#define NODE_COUNTER(p)
Get the counter of a node.
#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
#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.
@ Spanning_Tree
Definition aleph-graph.H:79
Main namespace for Aleph-w library functions.
and
Check uniqueness with explicit hash + equality functors.
static std::atomic< bool > init
Definition hash-fct.C:54
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
Distance accessor.
Dynamic doubly linked list implementation.
Utility algorithms and operations for graphs.