forked from codemistic/Data-Structures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode4.cpp
68 lines (58 loc) · 1.34 KB
/
code4.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
// Breadth first search
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int inf = 1e9 + 7;
void add_edge(vector<int> vec[], int u, int v)
{
vec[u].push_back(v);
vec[v].push_back(u);
}
void bfs(vector<int> vec[], int v, int source, vector<bool> &visited)
{
queue<int> q;
q.push(source);
visited[source] = true;
while (q.empty() == false)
{
int curr = q.front();
q.pop();
cout << curr << " ";
for (int i = 0; i < vec[curr].size(); i++)
{
int adjacent = vec[curr][i];
if (visited[adjacent] == false)
{
q.push(adjacent);
visited[adjacent] = true;
}
}
}
}
void bfs_recursive(vector<int> vec[], int v)
{
vector<bool> visited(v, false);
for (int i = 0; i < v; i++)
{
if (visited[i] == false)
{
bfs(vec, v, i, visited);
}
}
}
int main()
{
int v;
v = 6;
vector<int> adj[v];
// Adding edges from this point
add_edge(adj, 0, 1);
add_edge(adj, 0, 2);
add_edge(adj, 0, 3);
add_edge(adj, 1, 5);
add_edge(adj, 2, 5);
add_edge(adj, 1, 4);
cout << "Breadth First Search is: " << endl;
bfs_recursive(adj, v);
return 0;
}