From 750de18faa33ae862a3348a6679f32e1517a3d4b Mon Sep 17 00:00:00 2001 From: Stoycho Kyosev Date: Wed, 21 Dec 2022 18:44:34 +0200 Subject: add Seminar11 --- Seminar11/Graph-Impl/MatrixGraph/MatrixGraph.cpp | 92 ++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 Seminar11/Graph-Impl/MatrixGraph/MatrixGraph.cpp (limited to 'Seminar11/Graph-Impl/MatrixGraph/MatrixGraph.cpp') diff --git a/Seminar11/Graph-Impl/MatrixGraph/MatrixGraph.cpp b/Seminar11/Graph-Impl/MatrixGraph/MatrixGraph.cpp new file mode 100644 index 0000000..bf155a1 --- /dev/null +++ b/Seminar11/Graph-Impl/MatrixGraph/MatrixGraph.cpp @@ -0,0 +1,92 @@ +#include"MatrixGraph.h" + +using vertex_t = MatrixGraph::vertex_t; +using weight_t = MatrixGraph::weight_t; + +MatrixGraph::MatrixGraph(size_t v) { + data = std::vector>(v, std::vector(v, 0)); +} + +bool MatrixGraph::validVertex(vertex_t v) const { + return v < data.size(); +} + +bool MatrixGraph::adjacent(vertex_t from, vertex_t to) const { + if(!validVertex(from) || !validVertex(to)) + throw "Invalid vertex"; + + return data[from][to] > 0; +} + +void MatrixGraph::addDirectedEdge(vertex_t from, vertex_t to, weight_t w) { + if(!validVertex(from) || !validVertex(to)) + throw "Invalid vertex"; + + data[from][to] = w; +} + +void MatrixGraph::addEdge(vertex_t from, vertex_t to, weight_t w) { + addDirectedEdge(from, to, w); + addDirectedEdge(to, from, w); +} + +void MatrixGraph::addVertex() { + for(auto& v : data) + v.push_back(0); + + data.push_back(std::vector()); +} + +void MatrixGraph::removeEdge(vertex_t from, vertex_t to) { + if(!validVertex(from) || !validVertex(to)) + throw "Invalid vertex"; + + data[from][to] = 0; +} + +void MatrixGraph::removeVertex(vertex_t v) { + if(!validVertex(v)) + throw "Invalid vertex"; + + data.erase(data.begin() + v); + + for(auto& vertex : data) + vertex.erase(vertex.begin() + v); +} + +weight_t MatrixGraph::getWeight(vertex_t from, vertex_t to) const { + if(!validVertex(from) || !validVertex(to)) + throw "Invalid vertex"; + + return data[from][to]; +} + +std::vector MatrixGraph::getSuccessors(vertex_t from) const { + if(!validVertex(from)) + throw "Invalid vertex"; + + std::vector result; + + for (size_t i = 0; i < data.size(); i++) + if(data[from][i] > 0) + result.push_back(i); + + return result; +} + +std::vector MatrixGraph::getPredecessors(vertex_t from) const { + if(!validVertex(from)) + throw "Invalid vertex"; + + std::vector result; + + for (size_t i = 0; i < data.size(); i++) + if(data[i][from] > 0) + result.push_back(i); + + return result; +} + +size_t MatrixGraph::vertexCount() const { + return data.size(); +} \ No newline at end of file -- cgit v1.3.1-23-gd82d