77 lines
1.5 KiB
C++
77 lines
1.5 KiB
C++
#ifndef GRAPH_H_
|
|
#define GRAPH_H_
|
|
|
|
#include <map>
|
|
#include <set>
|
|
#include <ostream>
|
|
|
|
namespace graph {
|
|
|
|
// Forward declerations
|
|
template<typename T> class Graph;
|
|
template<typename T> std::ostream& operator<<(std::ostream& os, Graph<T>& G);
|
|
|
|
template<typename T>
|
|
class Graph {
|
|
public:
|
|
~Graph();
|
|
|
|
// Return true if there is a path from u to v
|
|
virtual bool contains(const T& u, const T& v) = 0;
|
|
|
|
// Add edge e(u,v)
|
|
virtual void insert(const T& u, const T& v) = 0;
|
|
|
|
// Remove edge e(u,v)
|
|
virtual void remove(const T& u, const T& v) = 0;
|
|
|
|
// Return num. of vertices
|
|
std::uint16_t V();
|
|
|
|
// Return num. of edges
|
|
std::uint16_t E();
|
|
|
|
// Adjacency matrix representation
|
|
std::map<T, std::set<T>> adjMatrix;
|
|
|
|
friend std::ostream& operator<<<>(std::ostream& os, Graph<T>& G);
|
|
};
|
|
|
|
template<typename T>
|
|
Graph<T>::~Graph() {
|
|
adjMatrix.clear();
|
|
}
|
|
|
|
template<typename T>
|
|
std::uint16_t Graph<T>::V() {
|
|
return static_cast<std::uint16_t>(adjMatrix.size());
|
|
}
|
|
|
|
template<typename T>
|
|
std::uint16_t Graph<T>::E() {
|
|
std::uint16_t edges = 0;
|
|
for (const auto& v : adjMatrix) {
|
|
edges += static_cast<std::uint16_t>(v.second.size());
|
|
}
|
|
return static_cast<std::uint16_t>(edges);
|
|
}
|
|
|
|
template<typename T>
|
|
std::ostream& operator<<(std::ostream& os, Graph<T>& G) {
|
|
os << "V: " << G.V() << " E: " << G.E() << '\n';
|
|
for (const auto& u : G.adjMatrix) {
|
|
if (!u.second.empty()) {
|
|
for (const auto& v : u.second) {
|
|
os << u.first << "->" << v << ' ';
|
|
}
|
|
os << '\n';
|
|
}
|
|
}
|
|
os << '\n';
|
|
return os;
|
|
}
|
|
|
|
} // namespace graph
|
|
|
|
|
|
#endif |