Move headers into include folder and add single header to include all reachability algorithms
This commit is contained in:
86
include/graph/graph.h
Normal file
86
include/graph/graph.h
Normal file
@@ -0,0 +1,86 @@
|
||||
#ifndef GRAPH_H_
|
||||
#define GRAPH_H_
|
||||
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <ostream>
|
||||
#include <ranges>
|
||||
|
||||
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 graph vertices
|
||||
auto vertices();
|
||||
|
||||
// Return num. of vertices
|
||||
std::uint16_t V();
|
||||
|
||||
// Return num. of edges
|
||||
std::uint16_t E();
|
||||
|
||||
// Adjacency matrix representation
|
||||
std::unordered_map<T, std::unordered_set<T>> adjList;
|
||||
|
||||
friend std::ostream& operator<<<>(std::ostream& os, Graph<T>& G);
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
Graph<T>::~Graph() {
|
||||
adjList.clear();
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
auto Graph<T>::vertices() {
|
||||
return std::views::keys(adjList);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
std::uint16_t Graph<T>::V() {
|
||||
return static_cast<std::uint16_t>(adjList.size());
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
std::uint16_t Graph<T>::E() {
|
||||
std::uint16_t edges = 0;
|
||||
for (const auto& u : vertices()) {
|
||||
edges += static_cast<std::uint16_t>(adjList[u].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 : this->vertices()) {
|
||||
if (!this->adjList[u].empty()) {
|
||||
for (const auto& v : this->adjList[u]) {
|
||||
os << u << "->" << v << ' ';
|
||||
}
|
||||
os << '\n';
|
||||
}
|
||||
}
|
||||
os << '\n';
|
||||
return os;
|
||||
}
|
||||
|
||||
} // namespace graph
|
||||
|
||||
|
||||
#endif
|
||||
Reference in New Issue
Block a user