-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGraph.cpp
124 lines (104 loc) · 2.62 KB
/
Graph.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
// Graph
// https://www.techiedelight.com/graph-implementation-using-stl/
#include <iostream>
#include <vector>
#include <queue>
class Edge
{
public:
int source;
int destination;
Edge(int s, int d) : source(s), destination(d) { }
};
class Graph
{
private:
std::vector<std::vector<int>> adjacenyList;
int vertices;
void print(std::vector<int>& sequence)
{
for (auto v : sequence) {
std::cout << v << " -> ";
}
std::cout << "\n";
}
void dfs(int vertex, std::vector<bool>& visited, std::vector<int>& sequence)
{
visited[vertex] = true;
sequence.push_back(vertex);
for (int u : adjacenyList[vertex]) {
if (visited[u] == false) {
dfs(u, visited, sequence);
}
}
}
void bfs(int vertex, std::vector<bool>& visited, std::vector<int>& sequence)
{
std::queue<int> q;
q.push(vertex);
visited[vertex] = true;
while (!q.empty()) {
int v = q.front();
q.pop();
sequence.push_back(v);
for (auto u : adjacenyList[v]) {
if (!visited[u]) {
visited[u] = true;
q.push(u);
}
}
}
}
public:
Graph(const std::vector<Edge>& edges, int N) : vertices(N)
{
adjacenyList.resize(vertices);
for (auto edge : edges) {
adjacenyList[edge.source].push_back(edge.destination);
}
}
void dfs()
{
std::vector<bool> visited(vertices);
std::vector<int> sequence;
for (int i = 0; i < vertices; ++i) {
if (visited[i] == false) {
dfs(i, visited, sequence);
}
}
print(sequence);
}
void bfs()
{
std::vector<bool> visited(vertices, false);
std::vector<int> sequence;
for (int i = 0; i < vertices; ++i) {
if (visited[i] == false) {
bfs(i, visited, sequence);
}
}
print(sequence);
}
void print()
{
for (int i = 0; i < vertices; ++i) {
std::cout << i << " --> ";
for (auto v : adjacenyList[i]) {
std::cout << v << " ";
}
std::cout << "\n";
}
}
};
int main()
{
std::vector<Edge> edges { {0, 12}, {1, 2}, {1, 7}, {1, 8}, {2, 3}, {2, 6}, {3, 4},
{3, 5}, {8, 9}, {8, 12}, {9, 10}, {9, 11} };
Graph graph(edges, 13);
graph.print();
std::cout << "DFS : ";
graph.dfs();
std::cout << "BFS : ";
graph.bfs();
return 0;
}