-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdradest_graph.cpp
More file actions
464 lines (414 loc) · 10.4 KB
/
dradest_graph.cpp
File metadata and controls
464 lines (414 loc) · 10.4 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
#include <limits.h>
#include "dradest_graph.h"
// parameterized constructor
dradestGraph::dradestGraph(int x)
{
V = x;
adj = new std::vector<int>[V];
std::cout << "graph constructed\n";
}
// copy constructor
dradestGraph::dradestGraph(const dradestGraph& drg)
{
V = drg.V;
adj = new std::vector<int> [V];
for(int i=0; i<V; ++i)
{
adj[i] = drg.adj[i];
}
}
// destructor
dradestGraph::~dradestGraph()
{
delete [] adj;
}
// adds an edge to the graph between nodes u and w
void dradestGraph::addEdge(int u, int w)
{
// safety check for index out of bounds
if(u >= V || w >= V)
{
std::cout << "Invalid edge " << u << " - " << w << "!\n";
return;
}
if(std::find(adj[u].begin(), adj[u].end(), w) == adj[u].end())
{
adj[u].push_back(w);
adj[w].push_back(u);
// TODO: replace with set later to keep adjacency lists sorted
std::sort(adj[u].begin(), adj[u].end());
std::sort(adj[w].begin(), adj[w].end());
}
else
{
std::cout << "edge " << u << " - " << w << " already exists!\n";
}
}
// prints adjacency list of the graph
void dradestGraph::printGraph()
{
for (int i=0; i < V; ++i)
{
std::cout << "Adjacency list of node " << i << ": ";
for (int j=0; j < adj[i].size(); ++j)
{
std::cout << adj[i].at(j) << (j==adj[i].size()-1 ? "\n" : " -> ");
}
}
}
// performs breadth first search starting from node n
std::vector<int> dradestGraph::BFS(int n)
{
// save bfs
std::vector<int> bfs;
// check if n is valid
if(n >= V){
std::cout << "Node " << n << " invalid. Exiting BFS.\n";
return bfs;
}
// mark all nodes as unvisited
bool *visited = new bool[V];
for(int i = 0; i < V; i++){
visited[i] = false;
}
// queue for breadth first search
std::queue<int> q;
// mark the starting node as visited and enqueue it
visited[n] = true;
q.push(n);
std::cout << "BFS from node " << n << ": ";
while(!q.empty())
{
// dequeue a node from queue
n = q.front();
std::cout << n << " ";
bfs.push_back(n);
q.pop();
// traverse all adjacent nodes of node n
for (auto it = adj[n].begin(); it != adj[n].end(); ++it)
{
if (!visited[*it]) // mark as visited and enqueue it
{
visited[*it] = true;
q.push(*it);
}
}
}
std::cout << "\n";
return bfs;
}
// performs depth first search, iteratively
std::vector<int> dradestGraph::iterativeDFS(int n)
{
// save dfs
std::vector<int> dfs;
// check if n is valid
if(n >= V){
std::cout << "Node " << n << " invalid. Exiting DFS.\n";
return dfs;
}
// mark all nodes as unvisited
bool *visited = new bool[V];
for(int i = 0; i < V; i++){
visited[i] = false;
}
// stack for depth first search
std::stack<int> stack;
// push the starting node unto stack
stack.push(n);
std::cout << "Iterative DFS from node " << n << ": ";
while (!stack.empty())
{
// pop a node from the stack
n = stack.top();
stack.pop();
if(visited[n]) // ignore it if it's already visited
{
continue;
}
// mark n as visited and print it
std::cout << n << " ";
dfs.push_back(n);
visited[n] = true;
// traverse adjacency list of node n in reverse order
for (auto it = adj[n].rbegin(); it != adj[n].rend(); ++it) {
if (!visited[*it]){
stack.push(*it);
}
}
}
std::cout << "\n";
return dfs;
}
// helper function for recursive depth first search
void dradestGraph::helpDFS(int n, bool visited[], std::vector<int>* dfs)
{
// mark the current node as visited and print it
visited[n] = true;
std::cout << n << " ";
dfs -> push_back(n);
// traverse adjacency list of current node
for(auto it = adj[n].begin(); it != adj[n].end(); ++it) {
if(!visited[*it]) {
helpDFS(*it, visited, dfs);
}
}
}
// performs depth first search, recursively
std::vector<int> dradestGraph::recursiveDFS(int n)
{
std::vector<int> dfs;
// check if n is valid
if(n >= V){
std::cout << "Node " << n << " invalid. Exiting DFS.\n";
return dfs;
}
std::cout << "Recursive DFS from node " << n << ": ";
// mark all the vertices as not visited
bool *visited = new bool[V];
for (int i = 0; i < V; i++) {
visited[i] = false;
}
// call the helper dfs function
helpDFS(n, visited, &dfs);
std::cout << "\n";
return dfs;
}
// helper function to detect a cycle in a graph reachable from node n
bool dradestGraph::helpCycle(int n, bool visited[], int parent)
{
// mark the current node as visited
visited[n] = true;
// traverse adjacent nodes
for (auto it = adj[n].begin(); it != adj[n].end(); ++it)
{
// recur for adjacent unvisited nodes
if (!visited[*it])
{
if (helpCycle(*it, visited, n))
{
return true;
}
}
// adjacent node visited and not a parent of current node
else if (*it != parent)
{
return true;
}
}
return false;
}
// detect a cycle in the graph using DFS
bool dradestGraph::hasCycle()
{
// initally, all nodes are not visited
bool *visited = new bool[V];
for (int i = 0; i < V; i++) {
visited[i] = false;
}
// call helpCycle() to detect a cycle in different DFS trees
for (int i = 0; i < V; i++) {
if (!visited[i])
{
if (helpCycle(i, visited, -1))
{
return true;
}
}
}
return false;
}
// uses path compression technique
// (i.e. keeps found root of i as its parent)
int dradestGraph::find(struct subset subsets[], int i)
{
if(subsets[i].parent != i)
{
subsets[i].parent = find(subsets, subsets[i].parent);
}
return subsets[i].parent;
}
// uses union by rank to do union of sets x and y
void dradestGraph::Union(struct subset subsets[], int x, int y)
{
// find root of x and y
int xroot = find(subsets, x);
int yroot = find(subsets, y);
// attach smaller rank tree under root of high rank tree
if (subsets[xroot].rank < subsets[yroot].rank)
{
subsets[xroot].parent = yroot;
}
else if (subsets[xroot].rank > subsets[yroot].rank)
{
subsets[yroot].parent = xroot;
}
// make one as root and increment its rank by one
else
{
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}
// detects a cycle using union-find
bool dradestGraph::containsCycle()
{
// create a working copy of adjacency list
std::vector<int> *wadj = new std::vector<int>[V];
for(int i=0; i<V; i++)
{
wadj[i] = adj[i];
}
// memory for creatng V subsets
struct subset* subsets = new subset[V];
// initialize all nodes to be in their own set
for (int i = 0; i < V; i++)
{
subsets[i].parent = i;
subsets[i].rank = 0;
}
// traverse adjacency list
for(int i=0; i<V; ++i)
{
// traverse adjacent nodes (i.e. edges) of the current node
for(auto it=wadj[i].begin(); it != wadj[i].end(); ++it)
{
int x = find(subsets, i);
int y = find(subsets, *it);
if(x == y)
{
return true;
}
Union(subsets, x, y);
// remove current node from y's list of adjacent nodes
auto index = std::lower_bound(wadj[*it].begin(), wadj[*it].end(), i);
wadj[*it].erase(index);
}
}
return false;
}
// returns minimum spanning tree using Prim's algorithm
std::vector<int>* dradestGraph::primMST()
{
// construct MST as an adjacency list
std::vector<int> *wadj = new std::vector<int>[V];
// set of included nodes in the MST
bool included[V];
for(int i=0; i<V; ++i) // initialize all to false
{
included[i] = false;
}
// include the first node in the MST
included[0] = true;
// keep track of nodes included so we can return early if needs be
int pushed = 1;
for(int i=0; i<V; ++i)
{
for(auto it=adj[i].begin(); it!=adj[i].end(); ++it)
{
if(!included[*it])
{
wadj[i].push_back(*it);
included[*it] = true;
pushed++;
}
if(pushed >= V)
{
return wadj;
}
}
}
return wadj;
}
// returns minimum spanning tree using Kruskal's algorithm
std::vector<int>* dradestGraph::kruskalMST()
{
// construct MST as an adjacency list
std::vector<int> *wadj = new std::vector<int>[V];
// memory for creatng V subsets
struct subset* subsets = new subset[V];
// initialize all nodes to be in their own set
for (int i = 0; i < V; i++)
{
subsets[i].parent = i;
subsets[i].rank = 0;
}
// keep track of edges added
int edges = 0;
// current node
int i = 0;
while(edges < V-1)
{
// traverse adjacent nodes of the current node (i)
for(auto it=adj[i].begin(); it!=adj[i].end(); ++it)
{
// check if this edge forms a cycle
int x = find(subsets, i);
int y = find(subsets, *it);
if(x != y)
{
// add the edge
wadj[i].push_back(*it);
// perform union on the two nodes
Union(subsets, x, y);
edges++;
}
}
i++;
}
return wadj;
}
// returns node with minimum distance value from nodes not yet included in shortest path tree
int dradestGraph::minDistance(int distance[], bool included[])
{
// Initialize min value
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
{
if (included[v] == false && distance[v] <= min)
{
min = distance[v];
min_index = v;
}
}
return min_index;
}
// prints shortest paths tree starting from root using Dijkstra's algorithm
void dradestGraph::dijkstraSPT(int root)
{
// set of included nodes in the MST
bool included[V];
int distance[V];
for(int i=0; i<V; ++i)
{
distance[i] = INT_MAX; // initialize all max value
included[i] = false; // initialize all to false
}
// include the first node in the SPT
distance[root] = 0;
// keep track of nodes included so we can return early if needs be
for(int i=0; i<V; ++i)
{
int u = minDistance(distance, included);
included[u] = true;
// traverse all adjacent nodes of u
for(auto it=adj[u].begin(); it!=adj[u].end(); ++it)
{
if(!included[*it] && distance[u] != INT_MAX && distance[u]+1 < distance[*it])
{
distance[*it] = distance[u]+1;
}
}
}
// print nodes and their distances from the root
std::cout << "Dijkstra starting from: " << root << " (node : distance)\n";
for(int i=0; i<V; ++i)
{
std::cout << i << " : " << distance[i] << "\n";
}
}