-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiGraphAdjList.cpp
More file actions
103 lines (91 loc) · 1.87 KB
/
DiGraphAdjList.cpp
File metadata and controls
103 lines (91 loc) · 1.87 KB
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
93
94
95
96
97
98
99
100
101
102
103
#include "DiGraphAdjList.h"
using namespace std;
namespace ds {
/**
* Determine if an edge is in graph
*
* @param s id of the source vertex
* @param t id of the target vertex
* @return true if the edge is in the graph
*/
bool DiGraphAdjList::hasEdge(int s, int t) const {
for (int &i : this->adj(s)) {
if (i == t) {
return true;
}
}
return false;
}
/**
* Add an edge to graph
*
* @param s id of the source vertex
* @param t id of the target vertex
*/
void DiGraphAdjList::addEdge(int s, int t) {
if (hasEdge(s, t) == false) {
adjList[s].addLast(t);
}
}
/**
* Remove an edge
*
* @param s id of the source vertex
* @param t id of the target vertex
*/
void DiGraphAdjList::delEdge(int s, int t) {
int i;
if (hasEdge(s, t) == true) {
for (int j = 0; j < adj(s).size(); j++) {
if (t == adjList[s].get(j)) {
i = j;
}
}
adjList[s].remove(i);
}
}
/**
* HELPER FUNCTION for hasCycle
*
* @return boolean
*/
bool hasCycleHelp(const DiGraphAdjList &g, int v, int *marked) {
// marked[v] = 0; // new
// marked[v] = 1; // active
// marked[v] = -1; // finished
marked[v] = 1;
for (int w = 0; w < g.adj(v).size(); w++) {
if (marked[w] == 1) {
return true;
}
else if (marked[w] == 0) {
if (hasCycleHelp(g, w, marked))
return true;
}
}
marked[v] = -1;
return false;
}
/**
* Check if the directed graph has cycles
*
* @return true if there are cycles
*/
bool DiGraphAdjList::hasCycle() const {
// TODO:
// create array called marked
int marked [v()];
for (int i = 0; i < v(); i++) {
marked[i] = 0;
}
for (int i = 0; i < v(); i++) {
if (marked[i] == 0)
if (hasCycleHelp(*this, i, marked))
return hasCycleHelp(*this, i, marked);
}
return false;
// Not Visited (NEW)
// Visited Once (ACTIVE)
// Done with DFS (FINISHED)
}
} // namespace ds