-
Notifications
You must be signed in to change notification settings - Fork 380
/
Copy pathbfstraversal.cpp
67 lines (49 loc) · 1.1 KB
/
bfstraversal.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
/*Given an undirected and connected graph G(V, E), print its BFS traversal.
Here you need to consider that you need to print BFS path starting from vertex 0 only.
V is the number of vertices present in graph G and vertices are numbered from 0 to V-1.
E is the number of edges present in graph G.*/
#include<iostream>
#include<queue>
using namespace std;
int main()
{
int V, E;
cin >> V >> E;
queue<int> q;
int** arr=new int*[V];
for(int i=0;i<V;i++)
{
arr[i]=new int[V];
}
for(int i=0;i<E;i++)
{
int v1,v2;
cin>>v1>>v2;
arr[v1][v2]=1;
arr[v2][v1]=1;
}
bool* visited=new bool[V];
for(int i=0;i<V;i++)
{
visited[i]=false;
}
q.push(0);
while(!q.empty())
{
int sv=q.front();
if(visited[sv]==false)
{
cout<<sv<<" ";
visited[sv]=true;
for(int i=0;i<V;i++)
{
if(arr[sv][i]==1)
{
q.push(i);
}
}
}
q.pop();
}
return 0;
}