Compiling and Running the Program
The next step is to compile and run the code. In the terminal, run the following command:
g++ main.cpp -o main && ./main
You should be able to see the output of the graph's BFS Traversal algorithm on the terminal.
Full code of the main.cpp
file
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
vector<bool> v;
vector<vector<int>> g;
void bfsTraversal(int b)
{
queue<int> q;
q.push(b);
v[b] = true;
cout << "\n\nThe BFS Traversal is: ";
while (!q.empty())
{
int a = q.front();
q.pop();
for (auto j = g[a].begin(); j != g[a].end(); j++)
{
if (!v[*j])
{
v[*j] = true;
q.push(*j);
}
}
cout << a << " ";
}
}
void makeEdge(int a, int b)
{
g[a].push_back(b);
}
int main()
{
int n, e, a, b, i;
cout << "Enter the number of vertices: ";
cin >> n;
cout << "Enter the number of edges: ";
cin >> e;
v.assign(n, false);
g.assign(n, vector<int>());
cout << "Enter the edges with source and target vertex: ";
for (i = 0; i < e; i++)
{
cin >> a >> b;
makeEdge(a, b);
}
for (i = 0; i < n; i++)
{
if (!v[i])
{
bfsTraversal(i);
}
}
return 0;
}