Skip to content

Commit a448886

Browse files
authored
Create bfs_traversal.cpp
1 parent 678621a commit a448886

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed

bfs_traversal.cpp

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
// C++ code to print BFS traversal from a given
2+
// source vertex
3+
4+
#include <bits/stdc++.h>
5+
using namespace std;
6+
7+
// This class represents a directed graph using
8+
// adjacency list representation
9+
class Graph {
10+
11+
// No. of vertices
12+
int V;
13+
14+
// Pointer to an array containing adjacency lists
15+
vector<list<int> > adj;
16+
17+
public:
18+
// Constructor
19+
Graph(int V);
20+
21+
// Function to add an edge to graph
22+
void addEdge(int v, int w);
23+
24+
// Prints BFS traversal from a given source s
25+
void BFS(int s);
26+
};
27+
28+
Graph::Graph(int V)
29+
{
30+
this->V = V;
31+
adj.resize(V);
32+
}
33+
34+
void Graph::addEdge(int v, int w)
35+
{
36+
// Add w to v’s list.
37+
adj[v].push_back(w);
38+
}
39+
40+
void Graph::BFS(int s)
41+
{
42+
// Mark all the vertices as not visited
43+
vector<bool> visited;
44+
visited.resize(V, false);
45+
46+
// Create a queue for BFS
47+
list<int> queue;
48+
49+
// Mark the current node as visited and enqueue it
50+
visited[s] = true;
51+
queue.push_back(s);
52+
53+
while (!queue.empty()) {
54+
55+
// Dequeue a vertex from queue and print it
56+
s = queue.front();
57+
cout << s << " ";
58+
queue.pop_front();
59+
60+
// Get all adjacent vertices of the dequeued
61+
// vertex s.
62+
// If an adjacent has not been visited,
63+
// then mark it visited and enqueue it
64+
for (auto adjacent : adj[s]) {
65+
if (!visited[adjacent]) {
66+
visited[adjacent] = true;
67+
queue.push_back(adjacent);
68+
}
69+
}
70+
}
71+
}
72+
73+
// Driver code
74+
int main()
75+
{
76+
// Create a graph given in the above diagram
77+
Graph g(4);
78+
g.addEdge(0, 1);
79+
g.addEdge(0, 2);
80+
g.addEdge(1, 2);
81+
g.addEdge(2, 0);
82+
g.addEdge(2, 3);
83+
g.addEdge(3, 3);
84+
85+
cout << "Following is Breadth First Traversal "
86+
<< "(starting from vertex 2) \n";
87+
g.BFS(2);
88+
89+
return 0;
90+
}

0 commit comments

Comments
 (0)