Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
kosaraju.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
50# ifndef KOSARAJU_H
51# define KOSARAJU_H
52
53# include <ah-graph-concepts.H>
54
55# include <tpl_dfs_stack.H>
56# include <tpl_graph_utils.H>
57
58namespace Aleph {
59
73namespace kosaraju_detail
74{
77 template <class GT>
78 struct Frame
79 {
80 typename GT::Node * p;
82
83 [[gnu::always_inline]] ALEPH_FLATTEN
84 Frame(const GT & g, typename GT::Node * n) : p(n), it(g.get_out_it(n)) {}
85
86 [[gnu::always_inline]] ALEPH_FLATTEN void next_arc() noexcept { it.next_ne(); }
87
88 // Moves the iterator to the next arc not visited whose target was not
89 // visited either, and gives that target; it marks the arcs not visited
90 // that it passes. nullptr when the arcs are done.
91 [[gnu::always_inline]] ALEPH_FLATTEN typename GT::Node * next_target() noexcept
92 {
93 for (; it.has_curr(); it.next_ne())
94 {
95 auto a = it.get_current_arc_ne();
97 continue;
98
99 // the target before the mark, which the compiler takes for a
100 // store that could change the iterator
101 auto tgt = it.get_tgt_node_ne();
102 ARC_BITS(a).set_bit(Depth_First, true);
103 if (not IS_NODE_VISITED(tgt, Depth_First))
104 return tgt;
105 }
106 return nullptr;
107 }
108 };
109
110 // Depth-first search from p, which visits and enters each node that it
111 // reaches, and leaves it when its arcs are done. A path can have as many
112 // nodes as the graph, too many for recursion, so that the search keeps
113 // its own stack; the order of the visits is that of a recursion. The
114 // node being visited keeps its iterator in a local frame until it visits
115 // a node; then it waits in the stack, where it goes on when it comes
116 // back.
117 template <class GT, class Enter, class Leave>
118 [[gnu::always_inline]] inline void
119 search(const GT & g, typename GT::Node * p, Enter enter, Leave leave)
120 {
122 return;
123
124 NODE_BITS(p).set_bit(Depth_First, true);
125 enter(p);
126
127 Dfs_Stack<Frame<GT>> frames;
128 Frame<GT> here(g, p);
129 while (true)
130 {
131 if (auto tgt = here.next_target())
132 { // the iterator stays on the arc to tgt, as in a recursion
133 NODE_BITS(tgt).set_bit(Depth_First, true);
134 enter(tgt);
135 frames.push(std::move(here));
136 here = Frame<GT>(g, tgt);
137 continue;
138 }
139
140 leave(here.p);
141 while (true) // back to the nodes that wait
142 {
143 if (frames.is_empty())
144 return;
145
146 Frame<GT> & f = frames.top();
147 f.next_arc(); // past the arc to the node that was visited
148 if (auto tgt = f.next_target())
149 {
150 NODE_BITS(tgt).set_bit(Depth_First, true);
151 enter(tgt);
152 here = Frame<GT>(g, tgt);
153 break;
154 }
155 leave(f.p);
156 frames.pop();
157 }
158 }
159 }
160} // namespace kosaraju_detail
161
162template <AlephGraph GT>
163inline static void __dfp_phase1(const GT & g,
164 typename GT::Node * p,
166{
167 kosaraju_detail::search(g, p, [](typename GT::Node *) {},
168 [&df](typename GT::Node * q)
169 {
170 df.append(q); // Append node in postorder (finish time)
171 NODE_COUNTER(q) = df.size();
172 });
173}
174
189template <AlephGraph GT>
190inline static void __dfp_phase2_subgraph(const GT & g,
191 typename GT::Node * p,
192 GT & blk,
193 const int & color)
194{
195 kosaraju_detail::search(g, p, [&blk, &color](typename GT::Node * q)
196 {
197 auto b = blk.insert_node(q->get_info());
198 NODE_COUNTER(b) = color;
199 GT::map_nodes(q, b);
200 },
201 [](typename GT::Node *) {});
202}
203
216template <AlephGraph GT>
217inline static void __dfp_phase2_list(const GT & g,
218 typename GT::Node * p,
220{
221 kosaraju_detail::search(g, p, [&list](typename GT::Node * q)
222 {
223 list.append(mapped_node<GT>(q));
224 },
225 [](typename GT::Node *) {});
226}
227
266template <AlephGraph GT>
267inline void kosaraju_connected_components(const GT & g,
268 DynList<GT> & blk_list,
270{
271 g.reset_nodes();
272 g.reset_arcs();
273
274 DynArray<typename GT::Node*> df; // Array for postorder (finish times)
275
276 // First DFS: compute finish times in postorder
277 for (auto it = g.get_node_it(); it.has_curr(); it.next_ne())
278 __dfp_phase1(g, it.get_curr(), df);
279
280 GT gi = invert_digraph(g); // Transposed graph
281
282 DynArray<GT*> array; // Array of subgraph pointers indexed by color
283
284 // Second DFS: process nodes in decreasing order of finish time
285 for (long i = static_cast<long>(df.size()) - 1, color = 0; i >= 0; --i)
286 {
287 auto gp = df.access(i);
288 auto bp = mapped_node<GT>(gp);
289 if (not IS_NODE_VISITED(bp, Depth_First))
290 {
291 GT & blk = blk_list.append(GT());
292 array[color] = &blk;
293
294 __dfp_phase2_subgraph(gi, bp, blk, color++); // DFS on transposed graph
295
296 assert(NODE_COLOR(mapped_node<GT>(bp)) == color - 1);
297 }
298
299 // gp was mapped to bp, of the transposed graph, which goes; now it
300 // maps to the node of its block, which already maps to gp
301 NODE_COOKIE(gp) = mapped_node<GT>(bp);
302 }
303
304 // Classify arcs: internal to SCC or crossing between SCCs
305 for (auto it = g.get_arc_it(); it.has_curr(); it.next_ne())
306 {
307 auto a = it.get_curr();
308 auto gs = g.get_src_node(a);
309 auto gt = g.get_tgt_node(a);
310
311 auto bs = mapped_node<GT>(gs); // the nodes of the blocks
312 auto bt = mapped_node<GT>(gt);
313
314 const long & color = NODE_COLOR(bs);
315
316 ARC_COOKIE(a) = nullptr; // it was mapped to the transposed graph
317 if (color == NODE_COLOR(bt))
318 {
319 // with the info of a, as the nodes of the block have theirs
320 typename GT::Arc * ba = array.access(color)->insert_arc(bs, bt, a->get_info());
321 GT::map_arcs(a, ba);
322 }
323 else
324 arc_list.append(a);
325 }
326}
327
357template <AlephGraph GT>
360{
362
363 g.reset_nodes();
364 g.reset_arcs();
365
366 DynArray<typename GT::Node*> df; // Array for postorder (finish times)
367
368 // First DFS: compute finish times in postorder
369 for (auto it = g.get_node_it(); it.has_curr(); it.next_ne())
370 __dfp_phase1(g, it.get_curr(), df);
371
372 GT gi = invert_digraph(g); // Transposed graph
373
374 // Second DFS: process nodes in decreasing order of finish time
375 for (long i = static_cast<long>(df.size()) - 1; i >= 0; --i)
376 {
377 auto gp = df.access(i);
378 auto bp = mapped_node<GT>(gp);
379 NODE_COOKIE(gp) = nullptr; // it mapped to bp, which goes with gi
381 continue;
382
383 auto & blk = list.append(DynList<typename GT::Node*>());
384
385 __dfp_phase2_list(gi, bp, blk);
386 }
387
388 // The arcs of g were mapped to the transposed graph, which goes now
389 g.for_each_arc([](auto a) { ARC_COOKIE(a) = nullptr; });
390
391 return list;
392}
393
405template <AlephGraph GT>
407{
414 void operator () (const GT & g,
415 DynList<GT> & blk_list,
416 DynList<typename GT::Arc *> & arc_list) const
417 {
418 kosaraju_connected_components(g, blk_list, arc_list);
419 }
420
430};
431
444template <AlephGraph GT>
445inline size_t kosaraju_scc_count(const GT & g)
446{
447 return kosaraju_connected_components(g).size();
448}
449
465template <AlephGraph GT>
466inline bool is_strongly_connected(const GT & g)
467{
468 if (g.get_num_nodes() <= 1)
469 return true;
470
471 return kosaraju_scc_count(g) == 1;
472}
473
474} // end namespace Aleph
475
476# endif // KOSARAJU_H
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.
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.
T & access(const size_t i) noexcept
Fast access without checking allocation and bound_min_clock checking.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Definition tpl_graph.H:535
NodeInfo & get_info() noexcept
Return a modifiable reference to the data contained in the node.
Definition graph-dry.H:753
void next_ne() noexcept(shows_ne)
next() without its check: the current arc must exist.
Definition graph-dry.H:3344
auto get_tgt_node_ne() const noexcept
Backward-compatible alias: return target node (same as get_node_ne()).
Definition graph-dry.H:3386
auto get_current_arc_ne() const noexcept
Definition graph-dry.H:3369
bool has_curr() const noexcept
Return true is the iterator has a current arc.
Definition graph-dry.H:3358
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
void for_each_arc(Operation &op) const
Unconditionally traverse all the arcs of graph and on each one perform an operation.
Definition graph-dry.H:1805
auto get_arc_it() const noexcept
Obtains an iterator to the arc of graph.
Definition graph-dry.H:3144
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_nodes() const
Reset all the nodes of graph (the control bits, the state, the counter and the cookie)
Definition graph-dry.H:1206
auto get_node_it() const noexcept
Obtains an iterator to the nodes of graph.
Definition graph-dry.H:3122
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
#define ARC_COOKIE(p)
Return the arc cookie
void kosaraju_connected_components(const GT &g, DynList< GT > &blk_list, DynList< typename GT::Arc * > &arc_list)
Compute strongly connected components using Kosaraju's algorithm.
Definition kosaraju.H:267
#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.
GT invert_digraph(const GT &g)
Compute the transpose (arc-reversed) digraph.
#define ARC_BITS(p)
Return the control bits of arc p.
#define NODE_COOKIE(p)
Return the node cookie
size_t kosaraju_scc_count(const GT &g)
Count the number of strongly connected components.
Definition kosaraju.H:445
#define NODE_COLOR(p)
Synonymous of NODE_COUNTER.
#define IS_ARC_VISITED(p, bit)
Determine whether the bit field is or not set to one.
bool is_strongly_connected(const GT &g)
Check if a directed graph is strongly connected.
Definition kosaraju.H:466
#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.
@ Depth_First
Definition aleph-graph.H:73
void search(const GT &g, typename GT::Node *p, Enter enter, Leave leave)
Definition kosaraju.H:119
Main namespace for Aleph-w library functions.
static void __dfp_phase1(const GT &g, typename GT::Node *p, DynArray< typename GT::Node * > &df)
Definition kosaraju.H:163
static void __dfp_phase2_subgraph(const GT &g, typename GT::Node *p, GT &blk, const int &color)
DFS on transposed graph that builds an SCC subgraph (Phase 2).
Definition kosaraju.H:190
static long & df(typename GT::Node *p)
Internal helper: DFS discovery time stored in NODE_COUNTER(p).
static void __dfp_phase2_list(const GT &g, typename GT::Node *p, DynList< typename GT::Node * > &list)
DFS on transposed graph that builds an SCC node list (Phase 2).
Definition kosaraju.H:217
static long & color(typename GT::Node *p)
Functor wrapper for Kosaraju's algorithm.
Definition kosaraju.H:407
void operator()(const GT &g, DynList< GT > &blk_list, DynList< typename GT::Arc * > &arc_list) const
Compute SCCs returning subgraphs and cross-arcs.
Definition kosaraju.H:414
A node that waits for the one that it visits, and the next of its outgoing arcs to look at.
Definition kosaraju.H:79
void next_arc() noexcept
Definition kosaraju.H:86
GT::Node * next_target() noexcept
Definition kosaraju.H:91
Frame(const GT &g, typename GT::Node *n)
Definition kosaraju.H:84
Stack of the frames of a depth-first search that does not recurse.
Utility algorithms and operations for graphs.