Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

UTKARSH

UPADHYAY A5
DSA ASSIGNMENT-8 18102278

Virtual Labs:

Ans1.
#include <bits/stdc++.h>
using namespace std;
class Graph
{
public:
map<int, bool> visited;
map<int, list<int>> adj;
void addEdge(int v, int w);
UTKARSH
void DFS(int v); UPADHYAY A5
void BFS(int v); 18102278
};
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w);
}

void Graph::DFS(int v)
{
visited[v] = true;
cout << v << " ";
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
if (!visited[*i])
DFS(*i);
}

void Graph::BFS(int s)
{
bool *visited = new bool[5];
for(int i=0;i<5; i++)
visited[i] = false;
list<int> queue;
visited[s] = true;
queue.push_back(s);
list<int>::iterator i;

while(!queue.empty())
{
s = queue.front();
cout << s << " ";
queue.pop_front();

for (i = adj[s].begin(); i != adj[s].end(); ++i)


{
if (!visited[*i]) UTKARSH
{ UPADHYAY A5
18102278
visited[*i] = true;
queue.push_back(*i);
}
}
}
}
int main()
{
Graph g;
g.addEdge(0, 1);
g.addEdge(0, 9);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(9, 3);

cout << "Following is Depth First Traversal"


" (starting from vertex 2) \n";
g.DFS(2);
cout<<"\n";
cout << "Following is Breadth First Traversal"
" (starting from vertex 2) \n";

g.BFS(2);

return 0;
}
Output:

UTKARSH
UPADHYAY A5
​ 18102278

Ans2.
#include <bits/stdc++.h> using namespace std;
void fn(list<list<int>> adjlist,

{
int* iN = new int[n](); int* ouT = new int[n]();

int n)
list<list<int> >::iterator nest_list;
int i = 0;

for(nest_list = adjlist.begin();
nest_list != adjlist.end();
nest_list++)
{
list<int> lst = *nest_list;

ouT[i] = lst.size();

for(auto it = lst.begin();
it != lst.end(); it++)

} i++;
}
UTKARSH
UPADHYAY A5
iN[*it]++; 18102278

int maxi=0,mini=INT_MAX;
int pos1=0,pos2=0;
cout<<"The in-degree and out-degree of nodes are-\n";
cout << "Vertex\t\tIn\t\tOut" << endl;
for(int k = 0; k < n; k++)
{
if(iN[k]>maxi)
{
pos1=k;
maxi=iN[k];
}
if(iN[k]<mini)
{
pos2=k;
mini=iN[k];
}
cout << k << "\t\t"
<< iN[k] << "\t\t"
<< ouT[k] << endl;
}
cout<<"The maximum in-degree is of node = "<<pos1<<"\n"<<"The minimum
in-degree is of node= "<<pos2<<"\n";
cout<<"Enter the node to find its degree\n";
int x1;
cin>>x1;

cout<<iN[x1]+ouT[x1]<<"\n";
}
int main()
{
list<list<int>> adjlist;
list<int> tmp;
tmp.push_back(1); UTKARSH
tmp.push_back(2); UPADHYAY A5
adjlist.push_back(tmp); 18102278
tmp.clear();
tmp.push_back(3);
adjlist.push_back(tmp);
tmp.clear();
tmp.push_back(0);
tmp.push_back(5);
tmp.push_back(6);
adjlist.push_back(tmp);
tmp.clear();
tmp.push_back(1);
tmp.push_back(4);
adjlist.push_back(tmp);
tmp.clear();
tmp.push_back(2);
tmp.push_back(3);
adjlist.push_back(tmp);
tmp.clear();
tmp.push_back(4);

tmp.push_back(6); adjlist.push_back(tmp);

tmp.push_back(5); adjlist.push_back(tmp); tmp.clear();


int n = adjlist.size(); fn(adjlist, n);
}

tmp.clear();

Output:
UTKARSH
UPADHYAY A5
18102278

You might also like