SANKET BABAR
211IT015
Q1) BFS traversal of graph-
#include <bits/stdc++.h>
using namespace std;
class graph{
public:
map<int, list<int>> gr;
void addEdge(int u, int v, bool dir){
gr[u].push_back(v);
if(dir==0){
gr[v].push_back(u);
}
}
void printGraph(){
for(auto i: gr){
cout<< i.first << "-> " ;
for(auto j:i.second){
cout<< j<< " ";
}
cout<<endl;
}
}
void bfs(int first, map<int,bool> &visited, vector<int> &res,
int &count){
queue<int> nums;
if(count>0){
cout<<endl<<"Next Disconnected part of graph "<<endl;
}
count++;
nums.push(first);
visited[first] = 1;
cout<<"visited : "<< first <<" And added in
queue"<<endl;
while(!nums.empty()){
int frontnode = nums.front();
nums.pop();
cout<<frontnode<<" is popped from queue."<<endl;
res.push_back(frontnode);
for(auto i:gr[frontnode]){
if(!visited[i]){
nums.push(i);
cout<<"visited : "<< i <<" And added in
queue"<<endl;
visited[i]=1;
}
}
if(nums.empty()==1){
cout<<"Queue is empty now..."<<endl;
}
}
return ;
}
};
int main(){
graph g;
int edges,nodes,first,q,count;
vector<int> res;
map<int,bool> visited;
count=0;
cout<<"Enter number of edges: "<<endl;
cin>>edges;
cout<<"Enter number of vertices: "<<endl;
cin>>nodes;
cout<<"Enter edges: "<<endl;
for(int i=0; i<edges;i++){
int u,v;
cin>> u >> v;
g.addEdge(u,v,0);
g.printGraph();
cout<<endl<<"BFS algorithm - ";
for(auto m:g.gr){
if(!visited[m.first]){
g.bfs(m.first,visited,res,count);
}
}
cout<<endl<< "BFS traversal of graph: "<<endl;
for(auto k:res){
cout<<k<<" ";
}
return 0;
}
OUTPUT-
Q2) DFS traversal-
#include <bits/stdc++.h>
using namespace std;
class graph{
public:
map<int, list<int>> gr;
void addEdge(int u, int v, bool dir){
gr[u].push_back(v);
if(dir==0){
gr[v].push_back(u);
}
}
void printGraph(){
for(auto i: gr){
cout<< i.first << "-> " ;
for(auto j:i.second){
cout<< j<< " ";
}
cout<<endl;
}
}
void DFS(int first, map<int,bool> &visited,vector<int> &res)
{
stack<int> stack;
stack.push(first);
cout<<"visited : "<< first <<" And pushed in stack."<<endl;
while (!stack.empty())
{
first = stack.top();
stack.pop();
if (!visited[first])
{
res.push_back(first);
cout<<first<<" is popped from stack."<<endl;
visited[first] = true;
}
for (auto i:gr[first]){
if (!visited[i]){
stack.push(i);
cout<<"visited : "<< i <<" And pushed in
stack."<<endl;
}
}
}
}
};
int main(){
graph g;
int edges,nodes,first,q,count;
vector<int> res;
map<int,bool> visited;
count=0;
cout<<"Enter number of edges: "<<endl;
cin>>edges;
cout<<"Enter number of vertices: "<<endl;
cin>>nodes;
cout<<"Enter edges: "<<endl;
for(int i=0; i<edges;i++){
int u,v;
cin>> u >> v;
g.addEdge(u,v,0);
g.printGraph();
cout<<"DFS algorithm: "<<endl;
for(auto i:g.gr){
if(!visited[i.first]){
g.DFS(i.first, visited,res);
}
}
cout<< "DFS traversal of graph: "<<endl;
for(auto k:res){
cout<<k<<" ";
}
return 0;
}
OUTPUT-