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

ASSIGNMENT-9

Nilesh Kumar

06116403222

Btech CSE

USICT

Question-1 WAP to implement BFS TRAVERSAL.

CODE:
#include <iostream>

#include <queue>

#include <vector>

using namespace std;

// Structure to represent a graph node

struct Node {

int data;

vector<Node*> neighbors;
bool visited;
Node(int value) : data(value), visited(false) {}

};

// Function to perform BFS traversal

void BFS(Node* start) {

// Queue to store the nodes yet to be visited

queue<Node*> q;

// Mark the start node as visited and push it to the queue

start->visited = true;

q.push(start);

cout << "BFS Traversal: ";

// Continue till the queue is not empty

while (!q.empty()) {

// Get the front node from the queue

Node* current = q.front();

q.pop();
// Process the current node
cout << current->data << " ";

// Visit all the neighbors of the current node

for (Node* neighbor : current->neighbors) {

// If the neighbor is not visited, mark it as visited and push it to the queue

if (!neighbor->visited) {

neighbor->visited = true;

q.push(neighbor);

int main() {

// Creating nodes for the graph

Node* node1 = new Node(1);

Node* node2 = new Node(2);

Node* node3 = new Node(3);

Node* node4 = new Node(4);

Node* node5 = new Node(5);


// Creating edges between nodes
node1->neighbors.push_back(node2);

node1->neighbors.push_back(node3);

node2->neighbors.push_back(node4);

node3->neighbors.push_back(node4);

node3->neighbors.push_back(node5);

node4->neighbors.push_back(node5);

// Starting BFS from node1

BFS(node1);

// Freeing memory

delete node1;

delete node2;

delete node3;

delete node4;

delete node5;

return 0;

OUTPUT:
Question-2 WAP to implement DFS traversal.

CODE:
#include <iostream>
#include <vector>
#include <stack>

using namespace std;

// Structure to represent a graph node


struct Node {
int data;

vector<Node*> neighbors;
bool visited;

Node(int value) : data(value), visited(false) {}


};

// Function to perform DFS traversal


void DFS(Node* start) {
// Stack to store the nodes yet to be visited
stack<Node*> s;
// Mark the start node as visited and push it to the stack

start->visited = true;
s.push(start);

cout << "DFS Traversal: ";

// Continue till the stack is not empty


while (!s.empty()) {

// Get the top node from the stack


Node* current = s.top();

s.pop();

// Process the current node


cout << current->data << " ";

// Visit all the unvisited neighbors of the current node

for (Node* neighbor : current->neighbors) {

// If the neighbor is not visited, mark it as visited and push it to the stack
if (!neighbor->visited) {

neighbor->visited = true;
s.push(neighbor);
}
}

}
}

int main() {

// Creating nodes for the graph


Node* node1 = new Node(1);
Node* node2 = new Node(2);
Node* node3 = new Node(3);
Node* node4 = new Node(4);
Node* node5 = new Node(5);

// Creating edges between nodes


node1->neighbors.push_back(node2);
node1->neighbors.push_back(node3);
node2->neighbors.push_back(node4);
node3->neighbors.push_back(node4);
node3->neighbors.push_back(node5);
node4->neighbors.push_back(node5);

// Starting DFS from node1


DFS(node1);
// Freeing memory
delete node1;
delete node2;
delete node3;
delete node4;
delete node5;

return 0;
}

OUTPUT:

Question-3 WAP to implement Prim's and Krushkal algorithm and


compute their time complexity.

CODE:
#include<iostream>

using namespace std;


// Number of vertices in the graph
const int V=6;

// Function to find the vertex with minimum key value


int min_Key(int key[], bool visited[])

{
int min = 999, min_index; // 999 represents an Infinite value

for (int v = 0; v < V; v++) {

if (visited[v] == false && key[v] < min) {


// vertex should not be visited
min = key[v];

min_index = v;
}
}
return min_index;
}

// Function to print the final MST stored in parent[]


int print_MST(int parent[], int cost[V][V])

{
int minCost=0;

cout<<"Edge \tWeight\n";
for (int i = 1; i< V; i++) {
cout<<parent[i]<<" - "<<i<<" \t"<<cost[i][parent[i]]<<" \n";
minCost+=cost[i][parent[i]];

}
cout<<"Total cost is"<<minCost;
}

// Function to find the MST using adjacency cost matrix representation


void find_MST(int cost[V][V])

{
int parent[V], key[V];
bool visited[V];

// Initialize all the arrays


for (int i = 0; i< V; i++) {

key[i] = 999; // 99 represents an Infinite value


visited[i] = false;
parent[i]=-1;

key[0] = 0; // Include first vertex in MST by setting its key vaue to 0.


parent[0] = -1; // First node is always root of MST
// The MST will have maximum V-1 vertices
for (int x = 0; x < V - 1; x++)
{
// Finding the minimum key vertex from the

//set of vertices not yet included in MST


int u = min_Key(key, visited);

visited[u] = true; // Add the minimum key vertex to the MST

// Update key and parent arrays

for (int v = 0; v < V; v++)

{
// cost[u][v] is non zero only for adjacent vertices of u //
visited[v] is false for vertices not yet included in MST // key[]
gets updated only if cost[u][v] is smaller than key[v] if
(cost[u][v]!=0 && visited[v] == false && cost[u][v] < key[v]) {

parent[v] = u;
key[v] = cost[u][v];
}
}

}
// print the final MST
print_MST(parent, cost);
}

// main function
int main()
{
int cost[V][V];
cout<<"Enter the vertices for a graph with 6 vetices";
for (int i=0;i<V;i++)

{
for(int j=0;j<V;j++)
{
cin>>cost[i][j];
}

find_MST(cost);

return 0;

OUTPUT:
* Time Complexity for Prim's algorithm
Prim's has a Time Complexity of O(V^2) , V being the number if
vertices and it can be improved upto O(ElogV) using Fibonacci Heaps.

* Krushkal algorithm

CODE:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

// Data structure to represent an edge in the graph


struct Edge {
int src, dest, weight;

};

// Comparator function to sort edges based on their weights


bool compareEdges(const Edge& e1, const Edge& e2) {
return e1.weight < e2.weight;

// Utility function for finding id of DSU (Disjoint Set Union) member


int getRoot (int i, int id[]) {

while (i != id[i]) {
i = id[i];
}

return i;

// Connected operation of DSU (Disjoint Set Union) data structure


bool connected (int p, int q, int id[]) {

return (getRoot(p, id) == getRoot(q, id));


}
// Union operation of DSU
void unionSet (int p, int q, int *id) {
int i = getRoot(p, id);

int j = getRoot(q, id);

id[i] = j;

// Kruskal's algorithm for finding MST

vector<Edge> kruskalMST(vector<Edge>& edges, int V) {


vector<Edge> MST; // to store the MST

int *id = new int[V];

for (int i=0; i<V; i++) {


id[i] = i;

// Sort the edges based on their weights


sort(edges.begin(), edges.end(), compareEdges);

int count = 0;

int i = 0;
while (count < V - 1 && i < edges.size()) {
int src = edges[i].src;
int dest = edges[i].dest;

// Check if adding the current edge forms a cycle


if (!connected(src, dest, id)) {

MST.push_back(edges[i]);
unionSet(src, dest, id);
count++;
}

i++;

return MST;

// Function to display the edges of the MST


void displayMST(const vector<Edge>& MST) {

cout<<"Minimum Spanning Tree Edges:"<<endl<<endl;

cout<<"Edge : Weight "<<endl;


for (const auto& edge : MST) {
cout<<edge.src<<" -- "<<edge.dest<<" : "<<edge.weight<<endl;
}
}

int main() {
int V = 6; // number of vertices in the graph
vector<Edge> edges = {

{0, 1, 4},
{0, 2, 3},

{1, 2, 1},

{1, 3, 2},

{2, 3, 4},
{3, 4, 2}
};

vector<Edge> MST = kruskalMST(edges, V);

displayMST(MST);

return 0;
}

OUTPUT:
* Time Complexity for Krushkal algorithm
The time complexity of Kruskal's Algorithm is O(ElogV), where E is the
number of edges in the graph. This complexity is because the
algorithm uses a priority queue with a time complexity of O(logE).
However, the space complexity of the algorithm is O(E), which is
relatively high.

Question-4 Differentiate between Prim's and Krushkal's algorithm.

* Prim's Algorithm

a. It startsto build the Minimum Spanning Tree from any vertex in


the graph.
b. It traverses one node more than one time to get the minimum
distance.
c. Prim's algorithm has a time complexity of O(V2). V being the
number of vertices and can be improved up to O(E log V) using
Fibonacci heaps.
d. Prim's algorithm gives connected component as well as it works
only on connected graph.
* Kruskal's Algorithm

a. It startsto build the Minimum Spanning Tree from the vertex


carrying minimum weight in the graph.
b. It traverses one node only once.
c. Kruskal's algorithm's time complexity is O(E log V). V being the
number of vertices.
d. Kruskal's algorithm can generate forest(disconnected components)
at any instant as well as it can work on disconnected components

You might also like