Skip to content

Instantly share code, notes, and snippets.

@sr6033
Last active August 11, 2018 17:57
Show Gist options
  • Select an option

  • Save sr6033/96264d03564baf854e9652a685a36c25 to your computer and use it in GitHub Desktop.

Select an option

Save sr6033/96264d03564baf854e9652a685a36c25 to your computer and use it in GitHub Desktop.
Breadth First Search using C++ STL
#include <bits/stdc++.h>
using namespace std;
vector <vector <int>> g; // Graph vector
vector <bool> v; // Visited nodes
// Directed Graph
void addEdge(int a, int b)
{
g[a].push_back(b);
}
void bfs(int u)
{
queue<int> q;
q.push(u);
v[u] = true; // visited
while(!q.empty())
{
int node = q.front();
q.pop();
cout << node << " ";
for(auto i = g[node].begin(); i != g[node].end(); i++)
{
if(!v[*i])
{
q.push(*i);
v[*i] = true;
}
}
}
}
int main()
{
int n, e;
cin >> n >> e;
v.assign(n, false);
g.assign(n, vector<int>());
int a, b;
for(int i = 0; i < e; i++)
{
cin >> a >> b;
addEdge(a,b);
}
// Checking for disconnected nodes
for(int i = 0; i < n; i++)
{
if(!v[i])
bfs(i);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment