forked from TheAlgorithms/C-Plus-Plus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.cpp
More file actions
73 lines (72 loc) · 1.19 KB
/
BFS.cpp
File metadata and controls
73 lines (72 loc) · 1.19 KB
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
#include <iostream>
using namespace std;
class graph
{
int v;
list<int> *adj;
public:
graph(int v);
void addedge(int src, int dest);
void printgraph();
void bfs(int s);
};
graph::graph(int v)
{
this->v = v;
this->adj = new list<int>[v];
}
void graph::addedge(int src, int dest)
{
src--;
dest--;
adj[src].push_back(dest);
//adj[dest].push_back(src);
}
void graph::printgraph()
{
for (int i = 0; i < this->v; i++)
{
cout << "Adjacency list of vertex " << i + 1 << " is \n";
list<int>::iterator it;
for (it = adj[i].begin(); it != adj[i].end(); ++it)
{
cout << *it + 1 << " ";
}
cout << endl;
}
}
void graph::bfs(int s)
{
bool *visited = new bool[this->v + 1];
memset(visited, false, sizeof(bool) * (this->v + 1));
visited[s] = true;
list<int> q;
q.push_back(s);
list<int>::iterator it;
while (!q.empty())
{
int u = q.front();
cout << u << " ";
q.pop_front();
for (it = adj[u].begin(); it != adj[u].end(); ++it)
{
if (visited[*it] == false)
{
visited[*it] = true;
q.push_back(*it);
}
}
}
}
int main()
{
graph g(4);
g.addedge(1, 2);
g.addedge(2, 3);
g.addedge(3, 4);
g.addedge(1, 4);
g.addedge(1, 3);
//g.printgraph();
g.bfs(2);
return 0;
}