Adding DAG implementation
This commit is contained in:
59
daggy/include/daggy/DAG.impl
Normal file
59
daggy/include/daggy/DAG.impl
Normal file
@@ -0,0 +1,59 @@
|
||||
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{});
|
||||
roots.insert(id);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
void DAG<T>::dropVertex(const T & id) {
|
||||
auto it = vertices.find(id);
|
||||
auto vert = vertices.extract(id);
|
||||
for (auto cid : vert.children) dropEdge(id, cid);
|
||||
for (auto pid : vert.parents) dropEdge(pid, id);
|
||||
|
||||
// Remove anything
|
||||
roots.extract(id);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
void DAG<T>::dropEdge(const T & from, const T & to) {
|
||||
auto & src = vertices.at(from);
|
||||
auto & dst = vertices.at(to);
|
||||
|
||||
src.children.extract(to);
|
||||
dst.parents.extract(from);
|
||||
|
||||
roots.extract(to);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
void DAG<T>::addEdge(const T & from, const T & to) {
|
||||
auto & src = vertices.at(from);
|
||||
auto & dst = vertices.at(to);
|
||||
|
||||
// Add the edge
|
||||
src.children.insert(to);
|
||||
dst.parents.insert(from);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
std::deque<T> DAG<T>::shortest_path(const T & from, const T & to) {
|
||||
std::deque<T> subpath;
|
||||
|
||||
if (from == to) return {to};
|
||||
|
||||
auto & src = vertices.at(from);
|
||||
|
||||
for (const auto & cid : src.children) {
|
||||
auto pth = shortest_path(cid, to);
|
||||
if (subpath.size() == 0 or subpath.size() > pth.size())
|
||||
subpath.swap(pth);
|
||||
}
|
||||
|
||||
subpath.push_front(from);
|
||||
|
||||
return subpath;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user