-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUdemy.h
More file actions
1446 lines (1395 loc) · 46.2 KB
/
Udemy.h
File metadata and controls
1446 lines (1395 loc) · 46.2 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
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
//
// Created by Ryan.Zurrin001 on 1/11/2022.
//
#ifndef GRAPH_CPP_UDEMY_H
#define GRAPH_CPP_UDEMY_H
#pragma ide diagnostic ignored "bugprone-branch-clone"
#pragma ide diagnostic ignored "readability-use-anyofallof"
#pragma ide diagnostic ignored "misc-no-recursion"
#include <bits/stdc++.h>
using namespace std;
// ___________________________begin graph node class____________________________
/**
* @brief The GraphNode class
* @tparam T the type of the node
*/
template <class T>
class GraphNode {
public:
T data;
list<pair<T, double>> neighbors;
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 = nullptr;
}
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;
}
void setParent(T parent_) { this->parent = parent_; }
void setDistance(double distance_) { this->distance = distance_; }
void setVisited(bool visited_) { this->visited = visited_; }
}; //___________________________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 {
unordered_map<T, GraphNode<T>*> nodes;
int V{};
int E{};
bool isDirected{};
bool isWeighted{};
void bfsUtil(T src,const bool* visited,const bool* recur);
void dfsUtil( T src, bool* visited, bool* recur);
void dfsUtil(T src, bool* visited);
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, const bool* visited,int* color);
int encode(int i, int j, int rows, int cols, bool rowMajor = true);
double pathLengthUtil(T node1, T node2);
public:
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);
void addVertex(T i);
void addEdge(T node1, T node2);
void addEdge(T node1, T node2, double weight);
void removeEdge(T node1, T node2);
void removeNode(T node);
void bfs( T src);
void dfs(T src);
void findBackEdges(vector<pair<T,T>>& backEdges);
void print();
void printAllGraphData();
bool isConnected();
bool hasCycle();
bool cycleFromVertex(T node);
bool isBipartite();
bool hasEdge(T node1, T node2);
bool directed() const;
int getV() const;
int getE() const;
double getWeight(T node1, T node2);
int getNumberOfComponents();
int degree(T node);
T getId(T node);
int minDistance(const int *pInt, const bool *pBoolean);
int getCombinations();
double pathLength(T node1, T node2);
unordered_map<T, GraphNode<T>*> getNodes() const;
vector<pair<T,T>> dijkstra(T src, T dest, bool print);
T 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<vector<T>> getComponents();
}; // ____________________________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;
} // ____________________________end graph constructor__________________________
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]);
}
}
}
}
}
}
/**
* @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);
}
} // ____________________________end graph constructor__________________________
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]);
}
} // ____________________________end graph constructor__________________________
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]);
}
} // ____________________________end graph constructor__________________________
/**
* @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]);
}
} // ____________________________end graph constructor__________________________
/**
* @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]));
}
}
} // ____________________________end graph constructor__________________________
/**
* @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];
}
} // ____________________________end graph constructor__________________________
/**
* @brief adds a vertex to the graph
* @param i : node to be added
*/
template<class T>
void Graph<T>::addVertex(T i) {
nodes[i] = new GraphNode<T>(i);
V++;
} // ____________________________end addVertex__________________________________
/**
* @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");
}
nodes[node1]->neighbors.push_back(make_pair(node2, 0));
if (!isDirected) {
nodes[node2]->neighbors.push_back(make_pair(node1, 0));
}
E++;
} // ___________________________end addEdge_____________________________________
/**
* @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");
}
nodes[node1]->neighbors.push_back(make_pair(node2, weight));
if (!isDirected) {
nodes[node2]->neighbors.push_back(make_pair(node1, weight));
}
E++;
} // _____________________________end addEdge___________________________________
/**
* @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--;
} // ________________________end removeEdge_____________________________________
/**
* @brief removes a vertex from the graph
* @param i : node to be removed
*/
template<class T>
void Graph<T>::removeNode( T node) {
if (nodes.find(node) == nodes.end()) {
throw invalid_argument("Node does not exist");
}
for ( auto neighbor : nodes[node]->neighbors) {
removeEdge(node, neighbor.first);
}
nodes.erase(node);
V--;
} // ________________________end removeNode_____________________________________
/**
* @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;
}
/**
* @brief prints the graph in adjacency list format
*/
template<class T>
void Graph<T>::print() {
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() {
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;
}
} // ________________________end printAllGraphData______________________________
/**
* @brief determines if the graph is connected
* @return : true if the graph is connected, false otherwise
*/
template<class T>
bool Graph<T>::isConnected() {
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>::hasCycle() {
bool* visited;
T parent = -1;
// set all nodes to unvisited
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 ( auto node : nodes) {
if (hasCycleUtil(node.first, visited, recStack, parent)) {
delete[] recStack;
return true;
}
}
} else {
return hasCycleUtil(0, visited, recStack, parent);
}
delete[] recStack;
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);
} // _____________________________end cycleFromVertex___________________________
/**
* @brief determines if the graph is bipartite
* @return : true if the graph is bipartite, false otherwise
*/
template<class T>
bool Graph<T>::isBipartite() {
int color[V];
bool *visited = new bool[V];
for (int i = 0; i < V; i++) {
visited[i] = false;
color[i] = -1;
}
for ( auto node : nodes) {
if (color[node.first] == -1) {
if (!isBipartiteUtil(node.first, visited, color)) {
return false;
}
}
}
return true;
} // _____________________________end isBipartite_______________________________
/**
* @brief determines if an edge exists between two nodes
* @param node1 : first node
* @param node2 : second node
* @return : true if an edge exists, false otherwise
*/
template<class T>
bool Graph<T>::hasEdge(T node1, T node2) {
if (nodes.find(node1) == nodes.end() || nodes.find(node2) == nodes.end()) {
throw invalid_argument("Node does not exist");
}
// iterate over the neighbors of node1
for ( auto neighbor : nodes[node1]->neighbors) {
if (neighbor.first == node2) {
return true;
}
}
return false;
} // _____________________________end findEdge__________________________________
/**
* @brief returns the isDirected property of the graph
* @return : true if the graph is directed, false otherwise
*/
template<class T>
bool Graph<T>::directed() const {
return this->isDirected;
} // ________________________end directed_______________________________________
/**
* @brief number of vertices in the graph
* @return : number of vertices in the graph
*/
template<class T>
int Graph<T>::getV() const {
return V;
} // ________________________end getV___________________________________________
/**
* @brief number of edges in the graph
* @return : number of edges in the graph
*/
template<class T>
int Graph<T>::getE() const {
return E;
} // ________________________end getE___________________________________________
/**
* @brief gets the minimum distance between a node and all other nodes and
* returns the shortest path distance
* @param pInt : pointer to an integer to store the shortest path distance
* @param pBoolean : pointer to a boolean to store the result of the function
* @return the min distance between the node and all other nodes
*/
template<class T>
int Graph<T>::minDistance(const int *pInt, const bool *pBoolean) {
int min = INT_MAX;
int min_index;
for (int v = 0; v < V; v++) {
if (pBoolean[v] == false && pInt[v] <= min) {
min = pInt[v];
min_index = v;
}
}
return min_index;
} // ________________________end minDistance____________________________________
/**
* @brief counts the total combination pairs that can be made from the graph
* @param C : the size of the combinations to be counted
* @return
*/
template<class T>
int Graph<T>::getCombinations() {
bool *visited = new bool[V]{false};
int total = V*(V - 1) / 2;
for (int i = 0; i < V; i++) {
if (!visited[i]) {
auto combos = traverse(i, visited);
total -= combos * (combos - 1) / 2;
}
}
return total;
} // ________________________end getCombonations_______________________________
/**
* @brief returns the length between vertices node1 and node2
* @param node1 : first node
* @param node2 : second node
* @return : length between the two nodes
*/
template<class T>
double Graph<T>::pathLength(T node1, T node2) {
if (nodes.find(node1) == nodes.end() || nodes.find(node2) == nodes.end()) {
throw invalid_argument("Node does not exist");
}
return pathLengthUtil(node1, node2);
} // ________________________end pathLength_____________________________________
/**
* @brief gets the weight of an edge between two nodes
* @param node1 : first node
* @param node2 : second node
* @return : weight of the edge
*/
template<class T>
double Graph<T>::getWeight( T node1, T node2) {
// nodes are out of bounds
if (node1 >= V || node2 >= V) {
return -1;
}
for ( auto neighbor : nodes[node1]->neighbors) {
if (neighbor.first == node2) {
return neighbor.second;
}
}
return -1;
} // ________________________end getWeight_____________________________________
/**
* @brief getter function for the nodes of the graph
* @return : unordered map of all the nodes in the graph
*/
template<class T>
unordered_map<T, GraphNode<T> *> Graph<T>::getNodes() const {
return nodes;
}// _________________________end getNodes_______________________________________
/**
* @brief algorithm to find the shortest path between two nodes
* @param src : source node
* @param dest : destination node
* @return : the shortest path between the two nodes
*/
template<class T>
T Graph<T>::dijkstra( T src,
T dest) {
if (nodes.find(src) == nodes.end()) {
throw invalid_argument("Source node does not exist");
}
if (nodes.find(dest) == nodes.end()) {
throw invalid_argument("Destination node does not exist");
}
if (src == dest) {
throw invalid_argument("Source and destination are the same");
}
vector<double> distances(V, INT_MAX);
set<pair<double, T>> s;
distances[src] = 0;
s.insert(make_pair(0, src));
while (!s.empty()) {
auto it = s.begin();
auto curNode = it->second;
auto distTilNow = it->first;
s.erase(it);
for ( auto node : nodes[curNode]->neighbors) {
auto neighbor = node.first;
auto currEdge = node.second;
if (distTilNow + currEdge < distances[neighbor]) {
auto f = s.find({distances[neighbor], neighbor});
if (f != s.end()) {
s.erase(f);
}
distances[neighbor] = distTilNow + currEdge;
s.insert({distances[neighbor], neighbor});
}
}
}
if (distances[dest] == INT_MAX) {
return -1;
}
return distances[dest];
} // ________________________end dijkstra_______________________________________
/**
* @brief algorithm to find the shortest path between two nodes
* @param src : source node
* @param dest : destination node
* @param print : true if the path should be printed, false otherwise
* @return : vector of nodes in the shortest path
*/
template<class T>
vector<pair<T,T>> Graph<T>::dijkstra( T src,
T dest,
bool print) {
if (nodes.find(src) == nodes.end()) {
throw invalid_argument("Source node does not exist");
}
if (nodes.find(dest) == nodes.end()) {
throw invalid_argument("Destination node does not exist");
}
if (src == dest) {
throw invalid_argument("Source and destination are the same");
}
vector<double> distances(V, INT_MAX);
set<pair<double, T>> s;
distances[src] = 0;
s.insert(make_pair(0, src));
vector<pair<T,T>> path;
while (!s.empty()) {
auto it = s.begin();
auto curNode = it->second;
auto distTilNow = it->first;
s.erase(it);
for ( auto node : nodes[curNode]->neighbors) {
auto neighbor = node.first;
auto currEdge = node.second;
if (distTilNow + currEdge < distances[neighbor]) {
auto f = s.find({distances[neighbor], neighbor});
if (f != s.end()) {
s.erase(f);
}
distances[neighbor] = distTilNow + currEdge;
s.insert({distances[neighbor], neighbor});
path.push_back({curNode,neighbor});
}
}
}
if (print) {
for ( auto p : path) {
cout << p.first << " -> " << p.second << " = " << distances[p.second] << endl;
}
}
return path;
} // ________________________end dijkstra_______________________________________
/**
* @brief finds the shortest path between two nodes, if it exists
* @param src : source node
* @param dest : destination node
* @param print : true if the path should be printed, false otherwise
* @return : vector of nodes in the shortest path, empty vector if no path exists
*/
template<class T>
vector<T> Graph<T>::shortestPath( T src,
T dest,
bool print) {
if (nodes.find(src) == nodes.end()) {
throw invalid_argument("Source node does not exist");
}
if (nodes.find(dest) == nodes.end()) {
throw invalid_argument("Destination node does not exist");
}
if (src == dest) {
vector<T> path;
path.push_back(src);
return path;
}
vector<T> path;
bool *visited = new bool[V];
bool *recStack = new bool[V];
for ( int i = 0; i < V; i++) {
visited[i] = false;
recStack[i] = false;
}
queue<T> q;
int* dist = new int[V]{0};
T* prev = new T[V]{-1};
q.push(src);
visited[src] = true;
dist[src] = 0;
while (!q.empty()) {
T u = q.front();
q.pop();
for ( auto neighbor : nodes[u]->neighbors) {
if (!visited[neighbor.first]) {
visited[neighbor.first] = true;
dist[neighbor.first] = dist[u] + 1;
prev[neighbor.first] = u;
q.push(neighbor.first);
}
}
}
if (visited[dest]) {
T u = dest;
while (u != src) {
path.push_back(u);
u = prev[u];
}
path.push_back(src);
reverse(path.begin(), path.end());
if (print) {
cout << "Shortest path from " << src << " to " << dest << " is: ";
for ( auto node : path) {
cout << node << " ";
}
cout << endl;
}
delete[] visited;
delete[] recStack;
delete[] dist;
delete[] prev;
return path;
} else {
cout << "No path from " << src << " to " << dest << endl;
delete[] visited;
delete[] recStack;
delete[] dist;
delete[] prev;
return path;
}
} // ________________________end shortestPath___________________________________
/**
* single source shortest path algorithm (SSSP) to find the shortest path from a
* source node to all other nodes in a unweighted graph
* @param src : source node
* @param print : true if the path should be printed, false otherwise
* @return : vector of nodes in the shortest path, empty vector if no path exists
*/
template<class T>
vector<vector<T>> Graph<T>::shortestPaths( T src,
bool print) {
if (nodes.find(src) == nodes.end()) {
throw invalid_argument("Source node does not exist");
}
// determine if the graph is weighted
bool weighted = false;
for ( auto node : nodes) {
for ( auto neighbor : node.second->neighbors) {
if (neighbor.second != 0) {
weighted = true;
continue;
}
}
}
if (print && weighted) {
cout << "***************************************************";
cout << "\nWARNING: This search does not incorporate weights."
<< "\nUse Dijkstra's algorithm for valid weighted search." << endl;
cout << "***************************************************\n";
}
vector<vector<T>> paths;
bool *visited = new bool[V];
bool *recStack = new bool[V];
for ( int i = 0; i < V; i++) {
visited[i] = false;
recStack[i] = false;
}
queue<T> q;
int* dist = new int[V]{0};
T* prev = new T[V]{-1};
q.push(src);
visited[src] = true;
dist[src] = 0;
while (!q.empty()) {
T u = q.front();
q.pop();
for ( auto neighbor : nodes[u]->neighbors) {
if (!visited[neighbor.first]) {
visited[neighbor.first] = true;
dist[neighbor.first] = dist[u] + 1;
prev[neighbor.first] = u;
q.push(neighbor.first);
}
}
}
for ( int i = 0; i < V; i++) {
if (visited[i]) {
vector<T> path;
T u = i;
while (u != src) {
path.push_back(u);
u = prev[u];
}
path.push_back(src);
reverse(path.begin(), path.end());
paths.push_back(path);
if (print) {
cout << "Shortest path from " << src << " to " << i << " is: ";
for ( auto node : path) {
cout << node << " ";
}
cout << endl;
}
}
}
delete[] visited;
delete[] recStack;
delete[] dist;
delete[] prev;
return paths;
} // ________________________end shortestPaths__________________________________
/**
* @brief method to find all the connected nodes of each component in the graph
* and store them in a vector of vectors
* @return vector of vectors of connected nodes
*/
template<class T>
vector<vector<T>> Graph<T>::getComponents() {
bool *visited = new bool[V];
for (int i = 0; i < V; i++) {
visited[i] = false;
}
vector<vector<T>> components;
for (int i = 0; i < V; i++) {
if (!visited[i]) {
vector<T> component;
findComponentsUtil(i, visited, component);
components.push_back(component);
}
}
delete[] visited;
return components;
} // ________________________end findAllComponents______________________________
//##############################################################################
//***************************PRIVATE METHODS************************************
//##############################################################################
// ___________________________bfsUtil___________________________________________
/**
* @brief private helper function to help with bfs traversals
* @param src source node
* @param visited vector of visited nodes
* @param recur vector representing a stack of nodes to keep track of what node
* a node was visited from
*/
template<class T>
void Graph<T>::bfsUtil(
T src, const bool* visited,
const bool* recur) {
if (nodes.find(src) == nodes.end()) {
throw invalid_argument("Source node does not exist");
}
queue<T> q;
q.push(src);
visited[src] = true;
recur[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;
if (!isDirected) {
recur[neighbor.first] = true;
}
}
}
}
} // ________________________end bfsUtil________________________________________
/**
* @brief private helper function to help with dfs traversals