Code for DFS Traversing of the graph in C++....
# include<bits/stdc++.h>
using namespace std;
void dfs (int node, vector<int>v, bool *vis, vector<int>*adj ){
if(vis[node] == true) return; // return if node already visited
vis[node]=true; // first task after enter to the particular node
v.push_back(node); // storing of visited node for maintaining DFS sequence
dfs(adj[node], v, vis , adj); // Recursion to Jump on the child of present Node
}
int main(){
int V, E ; // Number of vertices and edges respectively
vector<int> adj[V]; // Adjacency List to store Edges
cout<<"Enter number of vertices and Edges"<<endl;
cin>>V>>E;
bool vis[V] = { false} ; // Keep the record of visited node
for(int i=0;i<E;i++;)
{
int v1,v2;
adj[v1].push_back(v2); // Edge from v1 to v2
adj[v2].push_back(v1); // // Edge from v2 to v1
}
vector<int>dfs_Seq[V]; // Vector for storing DFS sequence
for(int = 0;i<V,i++){
if(vis[i]==true) continue;
dfs(i,dfs_Seq, vis, adj);
}
cout<<"The DFS order of Graph"<<endl;
for(int i =0;i< dfs_Seq.size();i++)
cout<<dfs_Seq[i]<<" "; // Printing of DFS sequence
return 0;
}
Comments
Post a Comment