Skip to content

Instantly share code, notes, and snippets.

@sr6033
Created August 12, 2018 06:13
Show Gist options
  • Select an option

  • Save sr6033/3d4a018fc0ae598616ca11f134e060c5 to your computer and use it in GitHub Desktop.

Select an option

Save sr6033/3d4a018fc0ae598616ca11f134e060c5 to your computer and use it in GitHub Desktop.
Depth First Search using C++ STL
#include <bits/stdc++.h>
using namespace std;
vector< vector <int>> g;
vector<bool> v;
// Undirected graph
void addEdge(int a, int b)
{
g[a].push_back(b);
g[b].push_back(a);
}
void dfsVisit(int u)
{
v[u] = true;
cout << u << " ";
for(auto i = g[u].begin(); i != g[u].end(); i++)
{
if(!v[*i])
dfsVisit(*i);
}
}
void dfs(int n)
{
for(int u = 0; u < n; u++)
{
if(!v[u])
dfsVisit(u);
}
}
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);
}
dfs(n);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment