Input:
The number of node(optional/removable) v , then the number of edges e, then the edges one by one and lastly the starting node.
Objective:
DFS algorithm
Using recursive method, hence no pushing and popping into any stack.
Input is taken by adjacency list approach
Using recursive method, hence no pushing and popping into any stack.
Input is taken by adjacency list approach
Approach:
Using c++ stl, vector (each element of the vector is a list of elements).
Try it here
#include <bits/stdc++.h>
#define MAX_SIZE 100
using namespace std;
void dfs(std::vector<int>*, int, bool*);
void dfs(vector <int> gph[MAX_SIZE], int ss, bool visited[MAX_SIZE])
{
visited[ss]=true;
cout<<" "<<ss<<endl;
//s.push(ss);
for(int j=0;j<gph[ss].size();j++)
{
int t=gph[ss][j];
if((visited[t])==false)
dfs(gph,gph[ss][j],visited);
//cout<<" "<<g[s][j]<<endl;
}
}
int main()
{
int v;
int e;
vector <int> g[MAX_SIZE];
bool visited[MAX_SIZE];
for(int i=0;i<v;i++)
{
visited[i]=false;
}
int start;
cin>>v;
cin>>e;
int x;
int y;
for(int i=0;i<e;i++)
{
cin>>x>>y;
g[x].push_back(y);
g[y].push_back(x); //because its undirected here
}
cin>>start;
dfs(g, start, visited);
return 0;
}