85 lines
1.9 KiB
C++
85 lines
1.9 KiB
C++
#ifndef DIGRAPH_H_
|
|
#define DIGRAPH_H_
|
|
|
|
#include "algorithm/breadth_first_search.h"
|
|
#include "graph.h"
|
|
|
|
namespace graph {
|
|
|
|
template <typename T> class Digraph : public Graph<T> {
|
|
public:
|
|
Digraph() = default;
|
|
|
|
explicit Digraph(std::unordered_map<T, std::unordered_set<T>> G);
|
|
|
|
// Return true if there is a path from u to v
|
|
bool contains(const T &u, const T &v);
|
|
|
|
// Add edge e(u,v)
|
|
void insert(const T &u, const T &v);
|
|
|
|
// Remove edge e(u,v)
|
|
void remove(const T &u, const T &v);
|
|
|
|
// Reverse graph directions
|
|
auto reverse();
|
|
|
|
//
|
|
auto contains(const T &u);
|
|
|
|
template <typename U>
|
|
friend std::ostream &operator<<(std::ostream &os, const Digraph<U> &G);
|
|
};
|
|
|
|
template <typename T>
|
|
Digraph<T>::Digraph(std::unordered_map<T, std::unordered_set<T>> G) {
|
|
this->adjList = G;
|
|
}
|
|
|
|
template <typename T> bool Digraph<T>::contains(const T &u, const T &v) {
|
|
return algo::BreadthFirstSearch<T>(this->adjList).query(u, v);
|
|
}
|
|
|
|
template <typename T> void Digraph<T>::insert(const T &u, const T &v) {
|
|
this->adjList[u].insert(v);
|
|
this->adjList[v];
|
|
}
|
|
|
|
template <typename T> void Digraph<T>::remove(const T &u, const T &v) {
|
|
this->adjList[u].erase(v);
|
|
}
|
|
|
|
template <typename T> auto Digraph<T>::reverse() {
|
|
std::unordered_map<T, std::unordered_set<T>> revMatrix;
|
|
|
|
for (const auto &u : this->vertices()) {
|
|
for (const auto &v : this->adjList[u]) {
|
|
revMatrix[v].insert(u);
|
|
}
|
|
}
|
|
|
|
return revMatrix;
|
|
}
|
|
|
|
template <typename T> auto Digraph<T>::contains(const T &u) {
|
|
return this->adjList.count(u);
|
|
}
|
|
|
|
template <typename T>
|
|
std::ostream &operator<<(std::ostream &os, Digraph<T> &G) {
|
|
os << "V: " << G.V() << " E: " << G.E() << '\n';
|
|
for (const auto &u : G.vertices()) {
|
|
if (!G.adjList[u].empty()) {
|
|
for (const auto &v : G.adjList[u]) {
|
|
os << u << "->" << v << ' ';
|
|
}
|
|
os << '\n';
|
|
}
|
|
}
|
|
os << '\n';
|
|
return os;
|
|
}
|
|
|
|
} // namespace graph
|
|
|
|
#endif |