forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Breadth_First_Search.cpp
106 lines (86 loc) · 1.67 KB
/
Breadth_First_Search.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
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class Graph
{
int numberVertex;
vector <int> *adjacency;
public:
// Constructor to initialise graph
Graph(int numberVertex)
{
this->numberVertex = numberVertex;
adjacency = new vector <int> [numberVertex];
}
// Function to add edge between source and destination
void addEdge(int source, int destination)
{
adjacency[source].push_back(destination);
}
// Function to perform Breadth First Search
void bfs(int starting);
};
void Graph::bfs(int starting)
{
bool visited[numberVertex];
for (int i = 0; i < numberVertex; i++)
visited[i] = false;
queue <int> queue_vertex;
visited[starting] = true;
queue_vertex.push(starting);
while (!queue_vertex.empty())
{
starting = queue_vertex.front();
cout << starting << " ";
queue_vertex.pop();
for (vector <int> :: iterator it = adjacency[starting].begin(); it != adjacency[starting].end(); ++it)
{
if(!visited[*it])
{
visited[*it] = true;
queue_vertex.push(*it);
}
}
}
}
int main()
{
// Number of vertices
int n;
cin >> n;
Graph graph(n);
int edges;
cin >> edges;
// Create edges between vertices
int u, v;
for (int i = 0; i < edges; i++)
{
cin >> u >> v;
graph.addEdge(u, v);
}
cout << "Breadth First Traversal is: ";
graph.bfs(0);
return 0;
}
/*
Input:
8
14
0 1
0 2
1 2
1 4
2 0
2 3
3 3
3 6
4 0
4 5
5 6
5 7
6 2
7 3
Output:
Breadth First Traversal is: 0 1 2 4 3 5 6 7
*/