Skip to content

Commit ee28415

Browse files
Generic get_reachable function
This takes as argument a set and a for_each_successor function. This can be used even by classes that do not inherit from grapht.
1 parent a41130c commit ee28415

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

src/util/graph.h

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -458,6 +458,34 @@ void grapht<N>::visit_reachable(node_indext src)
458458
nodes[index].visited = true;
459459
}
460460

461+
/// Add to `set` nodes that are reachable from `set`
462+
/// \param set: set of source nodes, must be a container with an
463+
/// `insert(const value_type&)` method.
464+
/// \param for_each_successor: function which given a node `n` and a function
465+
/// `f`, applies `f` on all successors of `n`.
466+
template <class Container, typename nodet = typename Container::value_type>
467+
void get_reachable(
468+
Container &set,
469+
const std::function<void(
470+
const typename Container::value_type &,
471+
const std::function<void(const typename Container::value_type &)> &)>
472+
&for_each_successor)
473+
{
474+
std::vector<nodet> stack;
475+
for(const auto &elt : set)
476+
stack.push_back(elt);
477+
478+
while(!stack.empty())
479+
{
480+
auto n = stack.back();
481+
stack.pop_back();
482+
for_each_successor(n, [&](const nodet &node) { // NOLINT
483+
if(set.insert(node).second)
484+
stack.push_back(node);
485+
});
486+
}
487+
}
488+
461489
template<class N>
462490
std::vector<typename N::node_indext>
463491
grapht<N>::get_reachable(node_indext src, bool forwards) const

0 commit comments

Comments
 (0)