forked from TARANG0503/DSA-Practice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbfs.cpp
76 lines (59 loc) · 1007 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
75
76
#include<iostream>
#include<list>
using namespace std;
class BFS_Graph
{
int V;
list<int> *adj;
public:
BFS_Graph(int V);
void createEdge(int v, int w);
void BFS(int s);
};
BFS_Graph::BFS_Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void BFS_Graph::createEdge(int v, int w)
{
adj[v].push_back(w);
}
void BFS_Graph::BFS(int s)
{
bool *visited = new bool[V];
for(int i = 0; i < V; i++)
visited[i] = false;
list<int> queue;
visited[s] = true;
queue.push_back(s);
list<int>::iterator i;
while(!queue.empty())
{
s = queue.front();
cout << s << " ";
queue.pop_front();
for (i = adj[s].begin(); i != adj[s].end(); ++i)
{
if (!visited[*i])
{
visited[*i] = true;
queue.push_back(*i);
}
}
}
}
int main()
{
BFS_Graph g(4);
g.createEdge(0, 1);
g.createEdge(0, 2);
g.createEdge(1, 2);
g.createEdge(2, 0);
g.createEdge(2, 3);
g.createEdge(3, 3);
cout << "Breadth First Search.... "
<< "(Vertex 2) \n";
g.BFS(2);
return 0;
}