Skip to content

Commit 9b65862

Browse files
committed
grapht: add get_reachable function
This simply performs a depth-first search of the graph starting from a nominated node and returns a vector of reachable indices.
1 parent aaa8513 commit 9b65862

File tree

1 file changed

+27
-11
lines changed

1 file changed

+27
-11
lines changed

src/util/graph.h

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,8 @@ class grapht
246246

247247
void visit_reachable(node_indext src);
248248

249+
std::vector<node_indext> get_reachable(node_indext src, bool forwards) const;
250+
249251
void make_chordal();
250252

251253
// return value: number of connected subgraphs
@@ -447,26 +449,40 @@ void grapht<N>::shortest_path(
447449
template<class N>
448450
void grapht<N>::visit_reachable(node_indext src)
449451
{
450-
// DFS
452+
std::vector<node_indext> reachable = get_reachable(src, true);
453+
for(const auto index : reachable)
454+
nodes[index].visited = true;
455+
}
456+
457+
template<class N>
458+
std::vector<typename N::node_indext>
459+
grapht<N>::get_reachable(node_indext src, bool forwards) const
460+
{
461+
std::vector<node_indext> result;
462+
std::vector<bool> visited(size(), false);
451463

452-
std::stack<node_indext> s;
464+
std::stack<node_indext, std::vector<node_indext>> s;
453465
s.push(src);
454466

455467
while(!s.empty())
456468
{
457-
node_indext n=s.top();
469+
node_indext n = s.top();
458470
s.pop();
459471

460-
nodet &node=nodes[n];
461-
node.visited=true;
472+
if(visited[n])
473+
continue;
462474

463-
for(typename edgest::const_iterator
464-
it=node.out.begin();
465-
it!=node.out.end();
466-
it++)
467-
if(!nodes[it->first].visited)
468-
s.push(it->first);
475+
result.push_back(n);
476+
visited[n] = true;
477+
478+
const auto &node = nodes[n];
479+
const auto &succs = forwards ? node.out : node.in;
480+
for(const auto succ : succs)
481+
if(!visited[succ.first])
482+
s.push(succ.first);
469483
}
484+
485+
return result;
470486
}
471487

472488
template<class N>

0 commit comments

Comments
 (0)