This commit is contained in:
Ian Roddis
2021-06-02 16:41:13 -03:00
parent 3d238df398
commit fbe77d03f9
2 changed files with 29 additions and 3 deletions

View File

@@ -6,6 +6,7 @@
#include <unordered_map>
#include <unordered_set>
#include <iterator>
#include <functional>
namespace daggy {
template<typename T>
@@ -20,7 +21,29 @@ namespace daggy {
void dropEdge(const T & src, const T & dst);
// Returns the path from {from} to {to}
std::deque<T> shortest_path(const T & from, const T & to);
std::deque<T> shortestPath(const T & from, const T & to);
// Traversal
// Traverse all nodes, calling f(id). If f() returns
// false, stop traversing this branch.
// Guarantees to only visit each vertex once.
void traverse(std::function<bool> f);
// Same as traverse, but starts the traversal at
// the given id.
void traverseFrom(T& id, std::function<bool> f);
// Peek at the next node
T & next() const;
// Get the next node and mark it visited
T & visit_next();
// Clear the visited flag, optionally for downstream
// vertices
void unvisit(T &id, bool cascade = true);
// Breadth First Iterator
struct Iterator {
@@ -32,12 +55,15 @@ namespace daggy {
};
private:
struct Vertex {
// It's a bit redundant to preserve both, but
// it makes it possible with and against the
// directions possible
std::unordered_set<T> parents;
std::unordered_set<T> children;
bool visited;
};
std::unordered_map<T, Vertex> vertices;

View File

@@ -2,7 +2,7 @@ template<typename T>
void DAG<T>::addVertex(T id) {
if (vertices.find(id) != vertices.end())
throw std::runtime_error("Vertex already exists in graph");
vertices.emplace(id, Vertex{});
vertices.emplace(id, Vertex{.visited = false});
roots.insert(id);
}
@@ -43,7 +43,7 @@ void DAG<T>::addEdge(const T & from, const T & to) {
}
template<typename T>
std::deque<T> DAG<T>::shortest_path(const T & from, const T & to) {
std::deque<T> DAG<T>::shortestPath(const T & from, const T & to) {
std::deque<T> subpath;
if (from == to) return {to};