-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathGraph_Traverse.cpp
107 lines (84 loc) · 1.76 KB
/
Graph_Traverse.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
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
/*
Using reachability algorithms (DFS/BFS) to traverse a graph.
*/
#include<iostream>
#include<map>
#include<list>
#include<unordered_set>
#include<queue>
using namespace std;
template <typename T>
class Graph {
bool directed;
map<T, list<T>> neighbourMap;
public:
Graph(bool directed=false) {
this->directed = directed;
}
void addEdge(T u, T v) {
neighbourMap[u].push_back(v);
if(!directed) neighbourMap[v].push_back(u);
}
void print() {
for(pair<T, list<T>> p : neighbourMap) {
cout << p.first << " : ";
for(T neighbour : p.second) {
cout << neighbour << " ";
}
cout << endl;
}
}
void iterativeBFS(T s, unordered_set<T>& visited) {
queue<T> q;
q.push(s);
visited.insert(s);
cout << "bfs(" << s << ") : ";
while(!q.empty()) {
T front = q.front(); q.pop();
cout << front << " ";
for(T neighbour : neighbourMap[front]) {
if(visited.find(neighbour) == visited.end()) {
q.push(neighbour);
visited.insert(neighbour);
}
}
}
cout << endl << endl;
}
void traverseBFS() {
unordered_set<T> visited;
int numComponents = 0;
for(pair<T, list<T>> vertex : neighbourMap) {
T vertexName = vertex.first;
if(visited.find(vertexName) == visited.end()) {
numComponents++;
iterativeBFS(vertexName, visited);
}
}
cout << "Number of components in the graph = " << numComponents << endl;
}
};
int main() {
Graph<int> g;
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
g.addEdge(2, 4);
g.addEdge(2, 5);
g.addEdge(3, 6);
g.addEdge(4, 6);
g.addEdge(4, 7);
g.addEdge(5, 7);
g.addEdge(6, 8);
g.addEdge(7, 8);
g.addEdge(9, 10);
g.addEdge(9, 11);
g.addEdge(10, 11);
g.addEdge(12, 13);
g.addEdge(14, 13);
g.print();
cout << endl;
g.traverseBFS();
return 0;
}