Skip to content

Commit 936bc02

Browse files
authored
Create BFS-ALGORITHM-USING-C++ (#372)
Here's a solution to opened issue BFS algorithm using c++ Please add hacktoberfest tag.
1 parent 5d2eb02 commit 936bc02

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

BFS-ALGORITHM-USING-C++

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
// BFS algorithm in C++
2+
3+
#include <iostream>
4+
#include <list>
5+
6+
using namespace std;
7+
8+
class Graph {
9+
int numVertices;
10+
list<int>* adjLists;
11+
bool* visited;
12+
13+
public:
14+
Graph(int vertices);
15+
void addEdge(int src, int dest);
16+
void BFS(int startVertex);
17+
};
18+
19+
// Create a graph with given vertices,
20+
// and maintain an adjacency list
21+
Graph::Graph(int vertices) {
22+
numVertices = vertices;
23+
adjLists = new list<int>[vertices];
24+
}
25+
26+
// Add edges to the graph
27+
void Graph::addEdge(int src, int dest) {
28+
adjLists[src].push_back(dest);
29+
adjLists[dest].push_back(src);
30+
}
31+
32+
// BFS algorithm
33+
void Graph::BFS(int startVertex) {
34+
visited = new bool[numVertices];
35+
for (int i = 0; i < numVertices; i++)
36+
visited[i] = false;
37+
38+
list<int> queue;
39+
40+
visited[startVertex] = true;
41+
queue.push_back(startVertex);
42+
43+
list<int>::iterator i;
44+
45+
while (!queue.empty()) {
46+
int currVertex = queue.front();
47+
cout << "Visited " << currVertex << " ";
48+
queue.pop_front();
49+
50+
for (i = adjLists[currVertex].begin(); i != adjLists[currVertex].end(); ++i) {
51+
int adjVertex = *i;
52+
if (!visited[adjVertex]) {
53+
visited[adjVertex] = true;
54+
queue.push_back(adjVertex);
55+
}
56+
}
57+
}
58+
}
59+
60+
int main() {
61+
Graph g(4);
62+
g.addEdge(0, 1);
63+
g.addEdge(0, 2);
64+
g.addEdge(1, 2);
65+
g.addEdge(2, 0);
66+
g.addEdge(2, 3);
67+
g.addEdge(3, 3);
68+
69+
g.BFS(2);
70+
71+
return 0;
72+
}

0 commit comments

Comments
 (0)