Commit 9ae4ac79 authored by Stian Jakobsen's avatar Stian Jakobsen
Browse files

Merge branch 'dfs_implementation' into 'master'

Merge: Depth First Search

See merge request sja044/dte-3603_template_source_base!6
parents 390f2447 d20c088a
......@@ -6,6 +6,8 @@
// stl
#include <vector>
#include <iterator>
#include <stack>
namespace dte3603::graph::algorithms
......@@ -16,7 +18,48 @@ namespace dte3603::graph::algorithms
typename Graph_T::vertex_descriptor const& start)
return {};
// Same principle as BFS, but instead of queue we use stack, and reversing
// to avoid recursion
// Partially inspired by
using VertexDescriptor = typename Graph_T::vertex_descriptor;
// Creating a reverse iterator type for our edge iterator
using RevIt = typename std::reverse_iterator<
typename boost::graph_traits<Graph_T>::out_edge_iterator>;
std::stack<VertexDescriptor> unvisited = {};
std::vector<VertexDescriptor> visited;
auto cur_v = start;
while (!unvisited.empty()) {
// creating our outer edge iterators
typename boost::graph_traits<Graph_T>::out_edge_iterator edge_begin,
boost::tie(edge_begin, edge_end) = boost::out_edges(cur_v, graph);
// reversing the iterators and iterating for them
for (RevIt riter(edge_end), rend(edge_begin); riter != rend; riter++) {
auto target_v = boost::target(*riter, graph);
// pushing the target to our unvisited stack if it isn't found in the
// vector
if (std::find(visited.begin(), visited.end(), target_v)
== visited.end()) {
if (!unvisited.empty()) {
// setting first element in stack as current and pushing it to vector if
// not already present
cur_v =;
if (std::find(visited.begin(), visited.end(), cur_v) == visited.end()) {
return visited;
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment