You are on page 1of 2

#include

#include
#include
#include
#include
#include

<iostream>
<fstream>
<vector>
<queue>
<stack>
<algorithm>

using namespace std;


/**
* For graph with a single weight use vector<vector<pair<int,int> > >
* For graph with a double weight use vector<vector<pair<int,pair<int,int> > > >
* The Queue/Stack elements must have the same type as those of the adjacency list
*/
vector<vector<int> > graph;
vector<bool> vis;
void BFS(int i){
queue<int> Q;
Q.push(i);
vis[i]=true;
cout
<<"Starting visiting (push to queue) : " <<
i+1
<<" Here You Can Make some stuff .."
<<
endl;
while (!Q.empty()){
int j=Q.front();
Q.pop();
cout <<"Processing the visited node (pop from queue) : " <<
<<" Here you can make some other stuff.."
<<
for (int k=0;k<graph[j].size();++k){
if (!vis[graph[j][k]]) {
Q.push(graph[j][k]);
vis[graph[j][k]]=true;
cout <<"Starting visiting (push to queue) : " <<
<<" Here You Can Make some stuff .."
<<
}
}
cout <<"Node : " <<
j+1
<<" has been completely visited! Here some extra stuff can
}
}
void DFS(int i){
stack<int> S;
S.push(i);
vis[i]=true;
cout
<<"Starting visiting (push to stack) : " <<
i+1
<<" Here You Can Make some stuff .."
<<
endl;
while (!S.empty()){
int j=S.top();
S.pop();
cout <<"Processing the visited node (pop from stack) : " <<
<<" Here you can make some other stuff.."
<<
for (int k=0;k<graph[j].size();++k){
if (!vis[graph[j][k]]) {
S.push(graph[j][k]);
vis[graph[j][k]]=true;
cout <<"Starting visiting (push to stack) : " <<
<<" Here You Can Make some stuff .."
<<
}
}
cout <<"Node : " <<
j+1
<<" has been completely visited! Here some extra stuff can
}
}

j+1
endl;

graph[j][k]+1
endl;

be done!"<<endl;

j+1
endl;

graph[j][k]+1
endl;

be done!"<<endl;

int main () {
ifstream cin("data.in");
int t,n,m,u,v;
//"t" is the number of test cases,
//"n" is the number of nodes and "m" is the number of edges
cin>>t;
while(t--){
cin>>n>>m;
graph.clear();
graph.resize(n);
vis.clear();
vis.resize(n);
fill_n(vis.begin(),n,false);
while (m--){
cin>>u>>v;
u--;
v--;
graph[u].push_back(v);
//for non oriented graphs add the reverse edge
graph[v].push_back(u);
}
//For connected non-oriented graphs or highly connected oriented graphs
cout<<"### New Test Case !!!"<<endl;
cout<<"Starting BFS ..."<<endl;
BFS(0);
cout<<"BFS terminated !"<<endl;
fill_n(vis.begin(),n,false); // clean vis for DFS
cout<<"Starting DFS ..."<<endl;
DFS(0);
cout<<"DFS terminated !"<<endl;
//For other graphs, given the number of node in the graph,
//we make a loop and invoke BFS or DFS for a node if it is not visited.
/*
for(int i=0;i<=n;i++){
if(!vis[i]){
BFS(i);
}
}
*/
}
return 0;
}

You might also like