-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbfs.cpp
60 lines (51 loc) · 1.17 KB
/
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
/*Reference - geeksforgeeks*/
#include<iostream>
#include<list>
#include<queue>
using namespace std;
class Graph
{
list<int> *AdjList;
int V;
public:
Graph(int size)
{
V = size;
AdjList = new list<int>[V];
}
void addEdge(int a, int b)
{
AdjList[a].push_back(b);
}
void BFS(int source)
{
bool visited[V];
for(int i = 0;i<V;i++)
visited[i] = false;
queue<int> Q;
Q.push(source);
while(!Q.empty())
{
int T = Q.front();
Q.pop();
visited[T] = true;
cout<<T<<' ';
list<int>::iterator it;
for(it = AdjList[T].begin(); it != AdjList[T].end(); ++it)
if(!visited[*it])
Q.push(*it);
}
}
};
int main()
{
Graph G(4);
G.addEdge(0,1);
G.addEdge(0,2);
G.addEdge(1,2);
G.addEdge(2,0);
G.addEdge(2,3);
G.addEdge(3,3);
G.BFS(0);
return 0;
}