-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathBFSTraversalGraphs.cpp
More file actions
54 lines (41 loc) · 902 Bytes
/
BFSTraversalGraphs.cpp
File metadata and controls
54 lines (41 loc) · 902 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
54
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
/*BFS Traversal of graph
Breadth First Search
also called level ordeer traversal
*/
class Graph{
map<int, list<int> > l;
public:
void addEdge(int x, int y){
l[x].push_back(y);
l[y].push_back(x);
}
void bfs(int src){
queue<int> q;
map<int, bool> visited;
q.push(src);
visited[src]= true;
while(!q.empty()){
int node= q.front();
q.pop();
cout<< node<< " ";
for(int nbr: l[node]){
if(!visited[nbr]){
q.push(nbr);
visited[nbr]= true;
}
}
}
}
};
int main() {
Graph g;
g.addEdge(0,1);
g.addEdge(1,2);
g.addEdge(2,3);
g.addEdge(3,4);
g.addEdge(4,5);
g.bfs(0);
}