DS 17 DFS
DS 17 DFS
template<typename T>
class Graph{
public:
Graph(){
}
void addEdge(T u, T v,bool bidir=true){
adjList[u].push_back(v);
if(bidir){
adjList[v].push_back(u);
}
}
void print(){
1
Bharatiya Vidya Bhavan’s
Sardar Patel Institute of Technology
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai-400058-India
(Autonomous College Affiliated to University of Mumbai)
SE-ETRX Sub- DS
//i.second is LL
for(T entry:i.second){
cout<<entry<<",";
}
cout<<endl;
}
}
void dfsHelper(T node,map<T,bool> &visited){
//Whenever to come to a node, mark it visited
visited[node] = true;
cout<<node<<" ";
int main(){
Graph<int> g;
int v,e,n,s;
2
Bharatiya Vidya Bhavan’s
Sardar Patel Institute of Technology
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai-400058-India
(Autonomous College Affiliated to University of Mumbai)
SE-ETRX Sub- DS
cout<<"Enter the number of Edges: ";
cin>>v;
for(int i=0;i<v;i++){
cout<<"Enter the source and destination: ";
cin>>e>>n;
g.addEdge(e,n);
}
cout<<"Enter the Source Node for DFS: ";
cin>>s;
g.dfs(s);
return 0;
}
Output: