-
Notifications
You must be signed in to change notification settings - Fork 0
/
bfs.cpp
74 lines (57 loc) · 899 Bytes
/
bfs.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
69
70
71
72
73
74
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5;
int visited[N];
vector<int>adj_list[N];
void bfs(int src){
queue<int>q;
visited[src] = 1;
q.push(src);
while(!q.empty()){
int head = q.front();
q.pop();
cout<<head<<endl;
for(int adj_node: adj_list[head]){
if(visited[adj_node] == 0){
visited[adj_node] = 1;
q.push(adj_node);
}
}
}
}
/*
0 --- 1 2 --- 3
| |
| |
5 --- 4
no of node -> 6
no of edge -> 6
list of adj node ->
0 1
2 3
1 5
2 4
5 4
*/
int main()
{
int nodes, edges;
cin>>nodes>>edges;
for(int i=0; i<edges; i++){
int u,v;
cin>>u>>v;
adj_list[u].push_back(v);
adj_list[v].push_back(u);
}
int src = 0;
bfs(src);
return 0;
}
/*
6 5
0 1
2 3
1 5
2 4
5 4
*/