Skip to content

Commit b2599e1

Browse files
authored
Merge pull request #786 from raunakjaiswal/breadth_first_search/raunakjaiswal
Added [Breadth_first_traversal][CPP]
2 parents 3d95bda + e48170c commit b2599e1

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
//@ raunak kumar jaiswal
2+
3+
#include <bits/stdc++.h>
4+
using namespace std;
5+
6+
void bfstraversal(vector<vector<int>>& g, vector<bool>& visited, vector<int>& ans, int node)
7+
{
8+
queue<int>qq;
9+
qq.push(node);
10+
visited[node] = true;
11+
while(!qq.empty())
12+
{
13+
auto it = qq.front();
14+
qq.pop();
15+
for(auto itt : g[it])
16+
{
17+
if(visited[itt]==false)
18+
{
19+
visited[itt] = true;
20+
qq.push(itt);
21+
}
22+
}
23+
ans.push_back(it);
24+
}
25+
26+
}
27+
28+
void makegraph( vector<vector<int>>& g, int num_edge)
29+
{
30+
for(int i=0;i<num_edge;i++)
31+
{
32+
int a,b;
33+
cin>>a>>b;
34+
g[a].push_back(b);
35+
g[b].push_back(a);
36+
}
37+
}
38+
39+
int main()
40+
{
41+
vector<vector<int>>g;
42+
vector<bool>visited;
43+
int num_node , num_edge;
44+
cout<<"Enter number of Node"<<endl;
45+
cin>>num_node;
46+
cout<<"Enter number of Edges"<<endl;
47+
cin>>num_edge;
48+
49+
g.assign(num_node,vector<int>());
50+
visited.assign(num_node, false);
51+
52+
cout<<"Enter the edges between vertex"<<endl;
53+
makegraph(g,num_edge);
54+
55+
vector<int>ans;
56+
57+
for (int i=0;i<num_node;i++)
58+
{
59+
if(visited[i]==false)
60+
bfstraversal(g,visited, ans, i);
61+
}
62+
cout<<"----- Traversal output---"<<endl;
63+
for(auto it: ans)
64+
{
65+
cout<<it<<" ";
66+
}
67+
68+
69+
70+
71+
}

0 commit comments

Comments
 (0)