1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
#include"MatrixGraph.h"
using vertex_t = MatrixGraph::vertex_t;
using weight_t = MatrixGraph::weight_t;
MatrixGraph::MatrixGraph(size_t v) {
data = std::vector<std::vector<weight_t>>(v, std::vector<weight_t>(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<weight_t>());
}
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<vertex_t> MatrixGraph::getSuccessors(vertex_t from) const {
if(!validVertex(from))
throw "Invalid vertex";
std::vector<vertex_t> result;
for (size_t i = 0; i < data.size(); i++)
if(data[from][i] > 0)
result.push_back(i);
return result;
}
std::vector<vertex_t> MatrixGraph::getPredecessors(vertex_t from) const {
if(!validVertex(from))
throw "Invalid vertex";
std::vector<vertex_t> 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();
}
|