-
Notifications
You must be signed in to change notification settings - Fork 0
/
Graph.h
2466 lines (2381 loc) · 78.9 KB
/
Graph.h
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#pragma ide diagnostic ignored "bugprone-branch-clone"
#pragma ide diagnostic ignored "readability-use-anyofallof"
#pragma ide diagnostic ignored "misc-no-recursion"
#pragma ide diagnostic ignored "hicpp-use-auto"
#ifndef GRAPH_CPP_GRAPH_H
#define GRAPH_CPP_GRAPH_H
#include <bits/stdc++.h>
using namespace std;
template<typename GraphNode>
class GraphNodeIterator {
public:
using ValueType = typename GraphNode::ValueType;
using PointerType = ValueType*;
using ReferenceType = ValueType&;
using ConstPointerType = const ValueType*;
using ConstReferenceType = const ValueType&;
public:
explicit GraphNodeIterator(GraphNode* node) : node_(node) {}
GraphNodeIterator(const GraphNodeIterator& other) : node_(other.node_) {}
GraphNodeIterator& operator=(const GraphNodeIterator& other) {
if (this != &other) {
node_ = other.node_;
}
return *this;
}
bool operator==(const GraphNodeIterator& other) const {
return node_ == other.node_;
}
bool operator!=(const GraphNodeIterator& other) const {
return node_ != other.node_;
}
GraphNodeIterator& operator++() {
node_ = node_->next_;
return *this;
}
GraphNodeIterator operator++(int) {
GraphNodeIterator temp(*this);
node_ = node_->next_;
return temp;
}
ReferenceType operator*() {
return node_->value_;
}
ConstPointerType operator->() const {
return &(node_->value_);
}
private:
GraphNode* node_;
};
template<typename Graph>
class GraphIterator {
public:
using ValueType = typename Graph::ValueType;
using PointerType = ValueType*;
using ReferenceType = ValueType&;
using GraphNodePtr = typename Graph::GraphNodePtr;
using ConstPointerType = const ValueType*;
using ConstReferenceType = const ValueType&;
public:
explicit GraphIterator(GraphNodePtr node) : node_(node) {}
GraphIterator(const GraphIterator& other) : node_(other.node_) {}
GraphIterator& operator=(const GraphIterator& other) {
node_ = other.node_;
return *this;
}
bool operator==(const GraphIterator& other) const {
return node_ == other.node_;
}
bool operator!=(const GraphIterator& other) const {
return node_ != other.node_;
}
bool operator>(const GraphIterator& other) const {
return node_ > other.node_;
}
bool operator<(const GraphIterator& other) const {
return node_ < other.node_;
}
GraphIterator& operator++() {
node_ = node_->next_;
return *this;
}
GraphIterator operator++(int) {
GraphIterator temp(*this);
node_ = node_->next_;
return temp;
}
ReferenceType operator*() {
return node_->value_;
}
ConstPointerType operator->() const {
return &(node_->value_);
}
private:
GraphNodePtr node_;
};
// ___________________________begin graph node class____________________________
/**
* @brief The GraphNode class
* @tparam T the type of the node
*/
template <class T>
class GraphNode {
public:
using ValueType = T;
using Iterator = typename vector<GraphNode<T>*>::iterator;
using ConstIterator = typename vector<GraphNode<T>*>::const_iterator;
using ReverseIterator = typename vector<GraphNode<T>*>::reverse_iterator;
using ConstReverseIterator = typename vector<GraphNode<T>*>::const_reverse_iterator;
using GraphNodePtr = GraphNode<T>*;
using GraphNodePtrConst = const GraphNode<T>*;
using GraphNodePtrConstPtr = const GraphNode<T>**;
public:
T data;
list<pair<int, double>> neighbors;
std::shared_ptr<T> parent;
bool visited{};
double distance{};
GraphNode() : data(0), parent(nullptr), visited(false), distance(0) {}
explicit GraphNode(T data) {
this->data = data;
this->visited = false;
this->distance = 0;
this->parent = std::make_shared<T>(0);
}
GraphNode(T data, T parent, double distance, bool visited) {
this->data = data;
this->parent = parent;
this->distance = distance;
this->visited = visited;
}
GraphNode(T data, T parent, double distance) {
this->data = data;
this->parent = parent;
this->distance = distance;
this->visited = false;
}
[[nodiscard]] int degree() const {
return neighbors.size();
}
bool hasEdge(GraphNode<T>* node1, GraphNode<T>* node2) {
for (auto& neighbor : node1->neighbors) {
if (neighbor.first == node2->data) {
return true;
}
}
return false;
}
// get edge
double getEdge(GraphNode<T>* node1, GraphNode<T>* node2) {
for (auto& neighbor : node1->neighbors) {
if (neighbor.first == node2->data) {
return neighbor.second;
}
}
return 0;
}
void setParent(T parent_) { this->parent = parent_; }
void setDistance(double distance_) { this->distance = distance_; }
void setVisited(bool visited_) { this->visited = visited_; }
// ________________________Iterator Methods_________________________________
Iterator begin() { return neighbors.begin(); }
Iterator end() { return neighbors.end(); }
[[nodiscard]] ConstIterator begin() const { return neighbors.begin(); }
[[nodiscard]] ConstIterator end() const { return neighbors.end(); }
[[nodiscard]] ConstIterator cbegin() const { return neighbors.cbegin(); }
[[nodiscard]] ConstIterator cend() const { return neighbors.cend(); }
ReverseIterator rbegin() { return neighbors.rbegin(); }
ReverseIterator rend() { return neighbors.rend(); }
[[nodiscard]] ConstIterator crbegin() const { return neighbors.rbegin(); }
[[nodiscard]] ConstIterator crend() const { return neighbors.rend(); }
// ______________________End Iterator Methods_______________________________
~GraphNode() {
neighbors.clear();
}
const auto &toString() {
// find node in list and print the data of the node
for (auto& neighbor : neighbors) {
if (neighbor.first == data) {
return neighbor.first;
}
}
}
const auto &getData() {
return data;
}
};
//______________________________end graph node class____________________________
/**
* @brief a comparator for the priority queue that compares the weights of two
* nodes
*/
template<class T>
class GraphNodeComparator {
public:
// compare the weights of two nodes
bool operator()(const pair<T, double> &a, const pair<T, double> &b) {
return a.second > b.second;
}
};
// ___________________end graph node comparator class___________________________
// _______________________________begin graph class_____________________________
template <class T>
class Graph {
public:
// __________________________Graph Constructors_____________________________
explicit Graph(bool isDirected_ = false);
explicit Graph(vector<vector<T>> grid, int numbVertices, bool isDirected = false);
explicit Graph(int vertices, bool isDirected = false);
Graph(int vertices, pair<T,T> edges, bool isDirected = false);
Graph(int vertices, tuple<T,T,double> w_edgs, bool isDirected = false);
explicit Graph( vector<T> nodes, bool isDirected_ = false);
explicit Graph(const string& fileName, char delimiter = ' ',
bool isDirected_ = false,
bool isWeighted_ = false);
Graph(T* nodes, int size, bool isDirected_ = false);
Graph(const Graph& other);
Graph(Graph&& other);
Graph& operator=(const Graph& other);
Graph& operator=(Graph&& other);
// __________________________Graph Destructor______________________________
~Graph();
// __________________________Graph Setter Methods__________________________
void addVertex(T i); // add a vertex to the graph
void addVertex(pair<int,T> i); // add a vertex to the graph
// add node to graph
void addNode(GraphNode<T>* node);
void addEdge(T node1, T node2); // add an edge to the graph
void addEdge(T node1, T node2, double weight); // add weighted edge
void addEdge(pair<int,T> node1, pair<int, T> node2); // add an edge to the graph
void addEdge(pair<int,T> node1, pair<int, T> node2, double weight);
void setData(T data_, int node); // set the data of a node
void setWeight(int node1, int node2, double weight_); // set the weight of an edge
// __________________________Graph Getter Methods__________________________
std::shared_ptr<GraphNode<T>> getVertex(T node) const;
[[nodiscard]] unordered_map<T, GraphNode<T>*> getNodes() const;
[[nodiscard]] int getV() const;
[[nodiscard]] int getE() const;
vector<T> getNeighbors(T node);
vector<vector<T>> getComponents();
T getId(T node);
double getAvgPathLength();
double getAvgDegree();
double getAvgClusteringCoefficient();
double getWeight(T node1, T node2);
int getNumberOfComponents();
int getDegree(T node);
int getCombinations();
vector<vector<T>> getAdjMatrix();
vector<pair<pair<T,T>,double>> getEdges();
vector<pair<T,T>> getBridges();
vector<T> getArticulationPoints();
Graph<T> getTranspose();
// ____________________Graph Removal Methods_______________________________
void removeEdge(T node1, T node2);
void removeVertex(T node);
void emptyGraph();
// _____________________Graph Boolean Methods______________________________
[[nodiscard]] bool directed() const;
bool connected();
bool cycle();
bool cycleFromVertex(T node);
bool bipartite();
bool hasEdge(T node1, T node2);
bool isTree();
bool isDAG();
// ____________________Graph Traversal Algorithms_____________________________
void bfs( T src);
void dfs(T src);
double dijkstra(T src, T dest);
vector<T> shortestPath(T src, T dest, bool print = false);
vector<vector<T>> shortestPaths(T src, bool print = false);
vector<pair<T,T>> dijkstra(T src, T dest, bool print);
// bellman ford
vector<pair<T,T>> bellmanFord(T src,bool print = false);
// ______________________Graph Misc. Methods_______________________________
void findBackEdges(vector<pair<T,T>>& backEdges);
int minDistance(const int *pInt, const bool *pBoolean);
double pathLength(T node1, T node2);
vector<T> topologicalSort();
vector<vector<T>> stronglyConnectedComponents();
// ______________________Graph Print Methods_______________________________
void print();
void printAllGraphData();
void printNodeData();
void iteratorPrinter();
//_________________________Iterator Class Methods____________________________
using ValueType = T;
using GraphIterator = typename unordered_map<T, GraphNode<T>*>::iterator;
using ConstGraphIterator = typename unordered_map<T, GraphNode<T>*>::const_iterator;
using GraphNodeIterator = typename GraphNode<T>::Iterator;
using ConstGraphNodeIterator = typename GraphNode<T>::ConstIterator;
using ReverseGraphNodeIterator = typename GraphNode<T>::ReverseIterator;
using ConstReverseGraphNodeIterator = typename GraphNode<T>::ConstReverseIterator;
using GraphNodeConstIterator = typename GraphNode<T>::ConstIterator;
GraphIterator begin() { return nodes.begin(); }
GraphIterator end() { return nodes.end(); }
ConstGraphIterator cbegin() const { return nodes.cbegin(); }
ConstGraphIterator cend() const { return nodes.cend(); }
GraphIterator find(T key) { return nodes.find(key); }
ConstGraphIterator find(T key) const { return nodes.find(key); }
private:
unordered_map<int, std::shared_ptr<GraphNode<T>>> nodes; // the graph
int V{}; // number of vertices
int E{}; // number of edges
bool isDirected{}; // is the graph directed
bool isWeighted{}; // is the graph weighted
double avgDegree{}; // average degree of the graph
double avgPathLenth{}; // average path length of the graph
double globalClusteringCoef{}; // global clustering coefficient of the graph
int deletedVertices{}; // number of vertices deleted from the graph
// __________________________Graph Helper Methods___________________________
double calculateAverageDegree();
double calculateAveragePathLength();
double clusteringCoef(std::shared_ptr<GraphNode<T>> node);
double calculateGlobalClusteringCoefficient();
void bfsUtil(T src, const bool* visited,const bool* recur);
void dfsUtil( T src, bool* visited, bool* recur);
void dfsUtil(T src, bool* visited);
void dfsUtil(int v, bool visited[], vector<T> &comp);
bool hasCycleUtil( T node, bool* visited, bool* recur, T parent);
bool isConnectedUtil( int i, bool* visited);
bool findComponentsUtil( int i, bool* visited, vector<T>& components);
int traverse( T u, bool* visited);
bool cycleFromVertexUtil(T node, bool* visited);
void findBackEdgesUtil( T node, bool* visited, bool* recur,
vector<pair<T,T>>& backEdges);
bool isBipartiteUtil( T node, bool* visited, int* color);
int encode(int i, int j, int rows, int cols, bool rowMajor = true);
double pathLengthUtil(T node1, T node2);
void fillOrder(int v, bool visited[], stack<T> &Stack);
void sccUtil(int u, int* disc, int* low, stack<T> *st, bool* stackMember,
vector<vector<T>> &scc);
void bridgeUtil(int u, bool* visited, int* disc, int* low, int* parent,
vector<pair<T,T>> &bridges);
void articulationPointUtil(int i, bool* visited, int* disc, int* low, int* parent,
vector<T>& articulationPoints);
};
// _______________________________end graph class_______________________________
// ____________________begin graph class function definitions___________________
// *****************************************************************************
/**
* @brief Graph constructor
* @param isDirected_ : default is false, set to true if graph is directed
*/
template <class T>
Graph<T>::Graph(bool isDirected_) {
isDirected = isDirected_;
V = 0;
E = 0;
isWeighted = false;
avgDegree = 0;
avgPathLenth = 0;
globalClusteringCoef = 0;
deletedVertices = 0;
}
template<class T>
Graph<T>::Graph(vector<vector<T>> grid, int numbVertices, bool isDirected) {
// create graph with grid
int rows = grid.size();
int cols = grid[0].size();
this->isDirected = isDirected;
this->isWeighted = true;
// add numVertices vertices to graph
for (int i = 0; i <= numbVertices-1; i++) {
this->addVertex(i);
}
// build arrays dx and dy to store the directions of the 4-connected neighbors
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
// each pos in grid has 4 neighbors to N E S W if in bounds and the weight
// is the value at that pos. use the encode to add neighbors to graph and weight
// to the value of the pos at the N E S W
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
for (int k = 0; k < 4; k++) {
int x = i + dx[k];
int y = j + dy[k];
int encodedIJ = encode(i, j, rows, cols);
int encodedXY = encode(x, y, rows, cols);
if (x >= 0 && x < rows && y >= 0 && y < cols) {
// use findEdge to make sure we don't add a duplicate edge
if (!hasEdge(encodedIJ, encodedXY)) {
this->addEdge(encodedIJ, encodedXY, grid[x][y]);
}
}
}
}
}
deletedVertices = 0;
}
/**
* @brief Graph constructor with number of vertices which will be set from
* zero to number of vertices - 1
* @param vertices : number of vertices
* @param isDirected_ : default is false, set to true if graph is directed
*/
template<class T>
Graph<T>::Graph(int vertices, bool isDirected_) {
isDirected = isDirected_;
isWeighted = false;
for (int i = 0; i < vertices; i++) {
addVertex(i);
}
deletedVertices = 0;
}
template<class T>
Graph<T>::Graph(int vertices, pair<T, T> edges, bool isDirected) {
isDirected = isDirected;
isWeighted = false;
for (int i = 0; i < vertices; i++) {
addVertex(i);
}
for (int i = 0; i < edges.first.size(); i++) {
addEdge(edges.first[i], edges.second[i]);
}
deletedVertices = 0;
}
template<class T>
Graph<T>::Graph(int vertices, tuple<T, T, double> w_edgs, bool isDirected) {
isDirected = isDirected;
isWeighted = true;
for (int i = 0; i < vertices; i++) {
addVertex(i);
}
for (int i = 0; i < get<0>(w_edgs).size(); i++) {
addEdge(get<0>(w_edgs)[i], get<1>(w_edgs)[i], get<2>(w_edgs)[i]);
}
deletedVertices = 0;
}
/**
* @brief Graph constructor with vector of nodes
* @param nodes : vector of nodes
* @param isDirected_ : default is false, set to true if graph is directed
*/
template<class T>
Graph<T>::Graph( vector<T> nodes,
bool isDirected_) {
isDirected = isDirected_;
isWeighted = false;
for (int i = 0; i < nodes.size(); i++) {
addVertex(nodes[i]);
}
}
/**
* @brief Graph constructor with a file name and delimiter
* @param fileName : file name
* @param delimiter : delimiter
* @param isDirected_ : default is false, set to true if graph is directed
*/
template<class T>
Graph<T>::Graph(const string& fileName,
char delimiter,
bool isDirected_, bool isWeighted_) {
isDirected = isDirected_;
isWeighted = isWeighted_;
ifstream file(fileName);
if (!file.is_open()) {
cout << "File not found" << endl;
return;
}
// if weighted graph, read in the weights or else read in the edges
if (isWeighted) {
string line;
while (getline(file, line)) {
stringstream ss(line);
string token;
vector<string> tokens;
while (getline(ss, token, delimiter)) {
tokens.push_back(token);
}
addEdge(stoi(tokens[0]), stoi(tokens[1]), stod(tokens[2]));
}
} else {
string line;
while (getline(file, line)) {
stringstream ss(line);
string token;
vector<string> tokens;
while (getline(ss, token, delimiter)) {
tokens.push_back(token);
}
addEdge(stoi(tokens[0]), stoi(tokens[1]));
}
}
deletedVertices = 0;
}
/**
* @brief Graph constructor with an array of nodes
* @param nodes : array of nodes
* @param size : size of array
* @param isDirected_ : default is false, set to true if graph is directed
*/
template<class T>
Graph<T>::Graph(T *nodes_, int size, bool isDirected_) {
isDirected = isDirected_;
isWeighted = false;
for (int i = 0; i < size; i++) {
addVertex(i);
this->nodes[i]->data = nodes_[i];
}
deletedVertices = 0;
}
/**
* @brief copy constructor
* @param other : graph to be copied
*/
template<class T>
Graph<T>::Graph(const Graph &other) { // copy constructor
isDirected = other.isDirected;
isWeighted = other.isWeighted;
deletedVertices = other.deletedVertices;
for (int i = 0; i < other.nodes.size(); i++) {
addVertex(other.nodes[i]->data);
}
// copy edges from other graph and if graph is weighted, copy weights
for (int i = 0; i < other.nodes.size(); i++) {
for (int j = 0; j < other.nodes[i]->edges.size(); j++) {
if (isWeighted) {
addEdge(i, other.nodes[i]->edges[j]->data,
other.nodes[i]->edges[j]->weight);
} else {
addEdge(i, other.nodes[i]->edges[j]->data);
}
}
}
}
/**
* @brief move constructor
* @param other : graph to be moved
*/
template<class T>
Graph<T>::Graph(Graph &&other) { // move constructor
isDirected = other.isDirected;
isWeighted = other.isWeighted;
deletedVertices = other.deletedVertices;
nodes = other.nodes;
other.nodes.clear();
}
/**
* @brief copy assignment operator
* @param other : graph to be copied
* @return : reference to this graph
*/
template<class T>
Graph<T> &Graph<T>::operator=(const Graph &other) { // copy assignment
if (this != &other) {
isDirected = other.isDirected;
isWeighted = other.isWeighted;
deletedVertices = other.deletedVertices;
nodes.clear();
for (int i = 0; i < other.nodes.size(); i++) {
addVertex(other.nodes[i]->data);
}
// copy edges from other graph and if graph is weighted, copy weights
for (int i = 0; i < other.nodes.size(); i++) {
for (int j = 0; j < other.nodes[i]->edges.size(); j++) {
if (isWeighted) {
addEdge(i, other.nodes[i]->edges[j]->data,
other.nodes[i]->edges[j]->weight);
} else {
addEdge(i, other.nodes[i]->edges[j]->data);
}
}
}
}
return *this;
}
/**
* @brief move assignment operator
* @tparam T
* @param other : graph to be moved
* @return : reference to this graph
*/
template<class T>
Graph<T> &Graph<T>::operator=(Graph &&other) { // move assignment
if (this != &other) {
isDirected = other.isDirected;
isWeighted = other.isWeighted;
deletedVertices = other.deletedVertices;
nodes = other.nodes;
other.nodes.clear();
}
return *this;
}
template<class T>
void Graph<T>::addVertex(pair<int, T> i) {
// add a vertex to the graph
if (nodes.find(i.first) != nodes.end()) {
return;
} else {
nodes[i.first] = std::make_unique<GraphNode<T>>(i.first);
nodes[i.first]->data = i.second;
}
V++;
}
/**
* @brief adds a vertex to the graph
* @param i : node to be added
*/
template<class T>
void Graph<T>::addVertex(T i) {
// check to see if the node already exists
if (nodes.find(i) != nodes.end()) {
return;
} else {
nodes[i] = std::make_shared<GraphNode<T>>(i);
//nodes[i] = new GraphNode<T>(i);
V++;
}
}
/**
* @brief adds an edge to the graph
* @param node1 : first node, in directed graph this is the tail
* @param node2 : second node, in directed graph this is the head\n
* if directed: node1 ---> node2
*/
template<class T>
void Graph<T>::addEdge(T node1, T node2) {
if (nodes.find(node1) == nodes.end() || nodes.find(node2) == nodes.end()) {
throw invalid_argument("One of the nodes does not exist");
}
// check to see if the edge already exists
for (auto &neighbor : nodes[node1]->neighbors) {
if (neighbor.first == node2) {
return;
}
}
nodes[node1]->neighbors.push_back(make_pair(node2, 0));
if (!isDirected) {
nodes[node2]->neighbors.push_back(make_pair(node1, 0));
}
E++;
}
/**
* @brief adds a weighted edge to the graph
* @param node1 : first node, in directed graph this is the tail
* @param node2 : second node, in directed graph this is the head\n
* @param weight : weight of the edge\n
* if directed: node1--(weight)-->node2
*/
template<class T>
void Graph<T>::addEdge(T node1, T node2, double weight) {
isWeighted = true;
if (nodes.find(node1) == nodes.end() || nodes.find(node2) == nodes.end()) {
throw invalid_argument("One of the nodes does not exist");
}
// check to see if the edge already exists
for (auto &neighbor : nodes[node1]->neighbors) {
if (neighbor.first == node2) {
return;
}
}
nodes[node1]->neighbors.push_back(make_pair(node2, weight));
if (!isDirected) {
nodes[node2]->neighbors.push_back(make_pair(node1, weight));
}
E++;
}
template<class T>
void Graph<T>::addEdge(pair<int, T> node1, pair<int, T> node2) {
if (nodes.find(node1.first) == nodes.end() || nodes.find(node2.first) == nodes.end()) {
throw invalid_argument("One of the nodes does not exist");
}
// check to see if the edge already exists
for (auto &neighbor : nodes[node1.first]->neighbors) {
if (neighbor.first == node2.first) {
return;
}
}
nodes[node1.first]->neighbors.push_back(make_pair(node2.first, node2.second));
if (!isDirected) {
nodes[node2.first]->neighbors.push_back(make_pair(node1.first, node1.second));
}
E++;
}
template<class T>
void Graph<T>::addEdge(pair<int, T> node1, pair<int, T> node2, double weight) {
isWeighted = true;
if (nodes.find(node1.first) == nodes.end() || nodes.find(node2.first) == nodes.end()) {
throw invalid_argument("One of the nodes does not exist");
}
// check to see if the edge already exists
for (auto &neighbor : nodes[node1.first]->neighbors) {
// if it is a string type then we need to compare the strings
if (neighbor.first == node2.first) {
return;
}
}
nodes[node1.first]->neighbors.push_back(make_pair(node2.first, weight));
if (!isDirected) {
nodes[node2.first]->neighbors.push_back(make_pair(node1.first, weight));
}
E++;
}
template<class T>
void Graph<T>::setData(T data_, int node) {
//check that the node exists
if (nodes.find(node) == nodes.end()) {
cout << "Node " << node << " does not exist" << endl;
return;
}
nodes[node]->data = data_;
}
template<class T>
void Graph<T>::setWeight(int node1, int node2, double weight_) {
//check that the node exists
if (nodes.find(node1) == nodes.end() || nodes.find(node2) == nodes.end()) {
cout << "Node " << node1 << " or " << node2 << " does not exist" << endl;
return;
}
//check that the edge exists
for (auto &neighbor : nodes[node1]->neighbors) {
if (neighbor.first == node2) {
cout << "Edge " << node1 << "-->" << node2 << " exist" << endl;
cout << "setting weight from " << neighbor.second << " to " << weight_ << endl;
neighbor.second = weight_;
return;
}
}
cout << "Edge " << node1 << "-->" << node2 << " does not exist" << endl;
}
/**
* @brief removes an edge from the graph
* @param node1 : first node
* @param node2 : second node
*/
template<class T>
void Graph<T>::removeEdge(T node1, T node2) {
if (nodes.find(node1) == nodes.end() || nodes.find(node2) == nodes.end()) {
throw invalid_argument("One of the nodes does not exist");
}
nodes[node1]->neighbors.remove_if([&](pair<T, double> neighbor) {
return neighbor.first == node2;
});
if (!isDirected) {
nodes[node2]->neighbors.remove_if([&](pair<T, double> neighbor) {
return neighbor.first == node1;
});
}
E--;
}
/**
* @brief removes a vertex from the graph
* @param i : node to be removed
*/
template<class T>
void Graph<T>::removeVertex( T node) {
// check to see if the node exists
if (nodes.find(node) == nodes.end()) {
throw invalid_argument("The node does not exist");
}
// remove all edges from the node
for (auto &neighbor : nodes[node]->neighbors) {
cout << "removing edge" << neighbor.first << endl;
nodes[neighbor.first]->neighbors.remove_if([&](pair<T, double> neighbor) {
return neighbor.first == node;
});
}
//delete nodes[node];
nodes.erase(node);
deletedVertices++;
V--;
}
template<class T>
void Graph<T>::emptyGraph() {
nodes.clear();
V = 0;
E = 0;
deletedVertices = 0;
}
/**
* @brief breadth first search
* @param src : source node to start search
*/
template<class T>
void Graph<T>::bfs( T src) {
if (nodes.find(src) == nodes.end()) {
throw invalid_argument("Source node does not exist");
}
queue<T> q;
bool* visited = new bool[V]{false};
q.push(src);
visited[src] = true;
while (!q.empty()) {
T node = q.front();
q.pop();
cout << node << " ";
for ( auto neighbor : nodes[node]->neighbors) {
if (!visited[neighbor.first]) {
q.push(neighbor.first);
visited[neighbor.first] = true;
}
}
}
cout << endl;
delete[] visited;
}
// ________________________________end bfs______________________________________
/**
* @brief depth first search
* @param src : source node to start search
*/
template<class T>
void Graph<T>::dfs( T src) {
if (nodes.find(src) == nodes.end()) {
throw invalid_argument("Source node does not exist");
}
bool* visited = new bool[V]{false};
dfsUtil(src, visited);
delete[] visited;
}
// _________________________________end dfs_____________________________________
template<class T>
void Graph<T>::findBackEdges(vector<pair<T, T>> &backEdges) {
bool *visited = new bool[V];
bool *recur = new bool[V];
for (int i = 0; i < V; i++) {
visited[i] = false;
recur[i] = false;
}
for (int i = 0; i < V; i++) {
if (!visited[i]) {
findBackEdgesUtil(i, visited, recur, backEdges);
}
}
delete[] visited;
delete[] recur;
}
// _________________________________end findBackEdges___________________________
/**
* @brief prints the graph in adjacency list format
*/
template<class T>
void Graph<T>::print() {
// print using iterator
for (auto node : nodes) {
cout << node.first << ": ";
for (auto neighbor : node.second->neighbors) {
cout << neighbor.first << " ";
}
cout << endl;
}
}
// ________________________end print____________________________________________
/**
* @brief prints the graph in adjacency matrix format with weights
*/
template<class T>
void Graph<T>::printAllGraphData() {
avgDegree = calculateAverageDegree();
avgPathLenth = calculateAveragePathLength();
globalClusteringCoef = calculateGlobalClusteringCoefficient();
cout << "V: " << V << endl;
cout << "E: " << E << endl;
// print the weights of the edges as well
for ( auto node : nodes) {
cout << node.first << ":";
for ( auto neighbor : node.second->neighbors) {
cout << "(" << neighbor.second << ")" << neighbor.first << ", ";
}
cout << endl;
}
// print out the average degree
cout << "Average degree: " << avgDegree << endl;
// print out the average path length
cout << "Average path length: " << avgPathLenth << endl;
// print out the global clustering coefficient
cout << "Global clustering coefficient: " << globalClusteringCoef << endl;
}
template<class T>
void Graph<T>::printNodeData() {
// use basic for loop to print out the data
for (int i = 0; i < V; i++) {
// check that the node exists
if (nodes.find(i) != nodes.end()) {
cout << "Node: " << i << endl;
cout << "Degree: " << nodes[i]->neighbors.size() << endl;
// print out the data of the node
cout << "Data: " << nodes[i]->data << endl;
cout << "Neighbors: ";
for (auto neighbor : nodes[i]->neighbors) {
cout << neighbor.first << " ";
}
cout << endl;
}
}
}
/**
* @brief determines if the graph is connected
* @return : true if the graph is connected, false otherwise
*/
template<class T>
bool Graph<T>::connected() {
if (V == 1) {
return true;
}
bool *visited = new bool[V];
for (int i = 0; i < V; i++) {
visited[i] = false;
}
isConnectedUtil(0, visited);
for (int i = 0; i < V; i++) {
if (!visited[i]) {
delete[] visited;
return false;
}
}
delete[] visited;
return true;
}
// _____________________________end isConnected_________________________________
/**
* @brief determines if the graph has a cycle
* @warning : this function does not work for disconnected undirected graphs
* @return : true if the graph has a cycle, false otherwise
*/
template<class T>
bool Graph<T>::cycle() {
T parent = -1;
// set all nodes to unvisited
bool *visited = new bool[V];
bool *recStack = new bool[V];
for ( int i = 0; i < V; i++) {
recStack[i] = false;
visited[i] = false;
}
if (isDirected) {
for ( const auto& node : nodes) {
if (hasCycleUtil(node.first, visited, recStack, parent)) {
delete[] recStack;
delete[] visited;
return true;
}
}
} else {
auto result = hasCycleUtil(0, visited, recStack, parent);
delete[] recStack;
delete[] visited;
return result;
}
delete[] recStack;
delete[] visited;
return false;
}
// _____________________________end hasCycle____________________________________
/**
* @brief determines if there is a cycle from the given node of a directed graph
* @warning this function is only valid for directed graphs
* @param node : node to start search from
* @return : true if there is a cycle, false otherwise
*/
template<class T>
bool Graph<T>::cycleFromVertex(T node) {
if (nodes.find(node) == nodes.end()) {
throw invalid_argument("Node does not exist");
}
bool *visited = new bool[V];
for (int i = 0; i < V; i++) {
visited[i] = false;
}
return cycleFromVertexUtil(node, visited);
}