-
Notifications
You must be signed in to change notification settings - Fork 0
/
digraph.cpp
56 lines (49 loc) · 1.5 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
#include "digraph.h"
Digraph::Digraph() {
}
void Digraph::addEdge(std::string x, std::string y) {
this->map[x].push_back(y);
}
void Digraph::_isAConnectedGraph(std::string v,
std::unordered_set <std::string>&visited) {
std::list<std::string> ady = this->map[v];
visited.insert(v);
for (auto &w : ady) {
if (visited.find(w) == visited.end()) {
_isAConnectedGraph(w, visited);
}
}
}
bool Digraph::isAConnectedGraph() {
std::unordered_set <std::string> visited;
_isAConnectedGraph(this->map.begin()->first, visited);
return visited.size() >= this->map.size();
}
bool Digraph::isCyclic() {
std::unordered_set <std::string> parents;
std::unordered_set <std::string> visited;
for (auto &vertex : this->map) {
if (visited.find(vertex.first) == visited.end()) {
if (_isCyclic(vertex.first, parents, visited)) return true;
}
}
return false;
}
bool Digraph::_isCyclic(std::string v,
std::unordered_set <std::string> &parents,
std::unordered_set <std::string>&visited) {
std::list<std::string> ady = this->map[v];
if (visited.find(v) != visited.end()) return false;
if (parents.find(v) != parents.end()) return true;
parents.insert(v);
for (auto &w : ady) {
if (visited.find(w) == visited.end()) {
if (_isCyclic(w, parents, visited)) return true;
}
}
parents.erase(v);
visited.insert(v);
return false;
}
Digraph::~Digraph() {
}