Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implementation of Depth First Search #680

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions Advanced/dfs.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// A Quick implementation of dfs using vectors

// Its time complexity is O(v+e).where v is number of vertex and e is number of edges.

#include <bits/stdc++.h>
#define pb push_back

using namespace std;

bool v[10]={0};
vector<int> g[20];

void edge(int a, int b)
{
g[a].pb(b);

g[b].pb(a); // for undirected graph add this line
}

void dfs(int u)
{

v[u]=true;

cout<<u<<endl;
for (auto x:g[u]){
if (!vis[x]){

dfs(x);
}
}

}


int main()
{
cout<<"Number of vertices<<endl;
int n;cin>>n;
cout<<"Number of edges"<<endl;
int e;cin>>e;

int a, b;
for (int i = 0; i < e; i++) {
cin >> a >> b;
edge(a, b);
}
dfs(1);


return 0;
}