-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs.cpp
More file actions
54 lines (48 loc) · 750 Bytes
/
bfs.cpp
File metadata and controls
54 lines (48 loc) · 750 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<bits/stdc++.h>
using namespace std;
template<typename T>
class graph{
map<T,list<T> >l;
public:
void addedge(int x,int y)
{
l[x].push_back(y); // bidirectional
l[y].push_back(x);
}
void bfs(T src){
queue<T>q;
map<T,int>vis;
q.push(src);
vis[src] = true;
while(!q.empty())
{
T temp=q.front();
q.pop();
cout<< temp <<" ";
for(int nbr : l[temp])
{
if(!vis[nbr])
{
q.push(nbr);
vis[nbr] = true;
}
}
}
}
};
int main()
{
graph<int> g;
g.addedge(2,1);
g.addedge(2,3);
g.addedge(3,2);
g.addedge(3,0);
g.addedge(1,2);
g.addedge(1,0);
g.addedge(0,1);
g.addedge(3,4);
g.addedge(4,3);
g.addedge(4,5);
g.addedge(5,4);
g.bfs(0);
}