forked from Vishal-Aggarwal0305/DSA-CODE
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbfs_adj_list.cpp
60 lines (54 loc) · 1.06 KB
/
bfs_adj_list.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
#include<iostream>
#include<vector>
#include<queue>
#include<map>
using namespace std;
// from the starting node
vector<int> bfs(vector<int> v[], int s, int start)
{
queue<int> q;
map<int , bool> explored;
cout<<0<<" ";
q.push(0);
vector<int> ans;
while (!q.empty())
{
int current = q.front();
explored[current] = true;
for (int i = 0; i <v[current].size(); i++)
{
if (explored[v[current][i]] == false)
{
ans.push_back(v[current][i]);
explored[v[current][i]] = true;
q.push(v[current][i]);
}
}
q.pop();
}
return ans;
}
int main()
{
int n,m;
cin>>m>>n;
vector<int> v[n+1];
for(int i=0;i<m;i++)
{
int a,b;
cin>>a>>b;
v[a].push_back(b);
v[b].push_back(a);
}
int start;
cin>>start;
vector<int> ans=bfs(v,n+1, start);
for(int i=0;i<n;i++)
cout<<ans[i]<<" ";
return 0;
}
5 4
0 1
0 2
0 3
2 4