From 44585ed339356d273c9af716d5f82f6a1a928efd Mon Sep 17 00:00:00 2001 From: Ian Roddis Date: Wed, 2 Jun 2021 13:55:12 -0300 Subject: [PATCH] Shortest path found --- daggy/include/daggy/DAG.hpp | 50 ++++++++++++------------------------- tests/unit_dag.cpp | 18 ++++++++++--- 2 files changed, 30 insertions(+), 38 deletions(-) diff --git a/daggy/include/daggy/DAG.hpp b/daggy/include/daggy/DAG.hpp index ab6162e..75a9272 100644 --- a/daggy/include/daggy/DAG.hpp +++ b/daggy/include/daggy/DAG.hpp @@ -1,56 +1,38 @@ #pragma once +#include #include #include #include namespace daggy { - - template + template class DAG { public: DAG() {} - void addVertex(I id, T && data); - void dropVertex(I id); - void updateVertex(I id, T && data); + void addVertex(T id); + void dropVertex(const T & id); - void addEdge(I src, I dst); - void dropEdge(I src, I dst); + void addEdge(const T & src, const T & dst); + void dropEdge(const T & src, const T & dst); + + // Returns the path from {from} to {to} + std::deque shortest_path(const T & from, const T & to); private: struct Vertex { - T data; - // It's a bit redundant to preserve both, but - // it makes it possible to traverse both ways as - // needed. - std::unordered_set parents; - std::unordered_set children; + // it makes it possible with and against the + // directions possible + std::unordered_set parents; + std::unordered_set children; }; - std::unordered_map vertices; + std::unordered_map vertices; + std::unordered_set roots; }; - template - void DAG::addVertex(I id, T && data) { - vertices.emplace(id, Vertex{std::move(data), {}}); - } +#include "DAG.impl" - template - void DAG::addEdge(I from, I to) { - auto src = vertices.find(from); - if (src == vertices.end()) - throw std::runtime_error("Invalid from during edge insertion"); - auto dst = vertices.find(to); - if (dst == vertices.end()) - throw std::runtime_error("Invalid dst during edge insertion"); - - // ensure that no cycles are introduced - - - // Add the edge - src->second.children.insert(to); - dst->second.parents.insert(from); - } } diff --git a/tests/unit_dag.cpp b/tests/unit_dag.cpp index ecc1cc6..493790d 100644 --- a/tests/unit_dag.cpp +++ b/tests/unit_dag.cpp @@ -5,10 +5,20 @@ #include "catch.hpp" TEST_CASE("DAG Basic Tests", "[dag]") { - daggy::DAG dag; + daggy::DAG dag; - dag.addVertex(0, "hello"); - dag.addVertex(1, "goodbye"); + dag.addVertex(0); + for (int i = 1; i < 10; ++i) { + dag.addVertex(i); + dag.addEdge(i-1, i); + } - dag.addEdge(0, 1); + dag.addEdge(5, 9); + + auto sp = dag.shortest_path(1,9); + std::cout << "Shortest path from 1 to 10: ("; + for (auto k : sp) { + std::cout << k << " -> "; + } + std::cout << std::endl; }