-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdigraph.cpp
72 lines (57 loc) · 1.68 KB
/
digraph.cpp
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
#include "digraph.h"
using namespace std;
void Digraph::addVertex(int v) {
// If it already exists, does nothing.
// Otherwise, adds v with an empty adjacency set.
nbrs[v];
}
void Digraph::addEdge(int u, int v) {
addVertex(v);
nbrs[u].insert(v); // will also add u to nbrs if it was not there already
}
bool Digraph::isVertex(int v) {
return nbrs.find(v) != nbrs.end();
}
bool Digraph::isEdge(int u, int v) {
// check that u is in the keys and that it's associated set contains v
return nbrs.find(u) != nbrs.end() && nbrs[u].find(v) != nbrs[u].end();
}
unordered_set<int>::const_iterator Digraph::neighbours(int v) const {
// this will crash the program if v is not a vertex
return nbrs.find(v)->second.begin();
}
unordered_set<int>::const_iterator Digraph::endIterator(int v) const {
// this will crash the program if v is not a vertex
return nbrs.find(v)->second.end();
}
int Digraph::numNeighbours(int v) {
// this will crash the program if v is not a vertex
return nbrs.find(v)->second.size();
}
int Digraph::size() {
return nbrs.size();
}
vector<int> Digraph::vertices() {
vector<int> v;
for (unordered_map<int, unordered_set<int>>::const_iterator it = nbrs.begin();
it != nbrs.end(); it++) {
v.push_back(it->first);
}
return v;
}
bool Digraph::isWalk(vector<int> walk) {
if (walk.size() == 0)
return false;
if (walk.size() == 1)
return isVertex(walk[0]);
for (vector<int>::size_type i=0; i<walk.size()-1; i++)
if (!isEdge(walk[i], walk[i+1]))
return false;
return true;
}
bool Digraph::isPath(vector<int> path) {
set<int> s(path.begin(), path.end());
if (s.size() < path.size())
return false;
return isWalk(path);
}