-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1_BFS_Traversal.cpp
More file actions
53 lines (43 loc) · 966 Bytes
/
1_BFS_Traversal.cpp
File metadata and controls
53 lines (43 loc) · 966 Bytes
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
#include <bits/stdc++.h>
using namespace std;
vector <int> v[1005]; //maximum number of node will be the size
bool visAr[1005]; //boolean type visited array
void bfs(int src)
{
queue <int> q;
q.push(src);
visAr[src] = true;
while(!q.empty())
{
int par = q.front();
q.pop();
cout << par << endl;
for(int child : v[par])
{
if(visAr[child] == false)
{
q.push(child);
visAr[child] = true;
}
}
}
}
int main()
{
int n, e;
cin >> n >> e;
while(e--)
{
int a, b;
cin >> a >> b;
v[a].push_back(b);
v[b].push_back(a);
}
int src;
cin >> src;
memset(visAr, false, sizeof(visAr));
bfs(src);
return 0;
}
//Time complexity of bfs: O(node number + edge number) //O(v+e)
//Space complexity: O(node number)