0% found this document useful (0 votes)
14 views9 pages

Task 5

The document contains a lab assignment by Sohil Sheth for CSE2003-Data Structures and Algorithms, detailing implementations of Prim's algorithm for minimum spanning trees, Dijkstra's algorithm for shortest paths, selection sort, and breadth-first search (BFS) traversal. Each section includes an algorithm description followed by code implementations in C++. The assignment aims to demonstrate understanding and application of fundamental data structures and algorithms.

Uploaded by

sohilsheth21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views9 pages

Task 5

The document contains a lab assignment by Sohil Sheth for CSE2003-Data Structures and Algorithms, detailing implementations of Prim's algorithm for minimum spanning trees, Dijkstra's algorithm for shortest paths, selection sort, and breadth-first search (BFS) traversal. Each section includes an algorithm description followed by code implementations in C++. The assignment aims to demonstrate understanding and application of fundamental data structures and algorithms.

Uploaded by

sohilsheth21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Name: Sohil Sheth

Reg. No: 20BML0010

LAB ASSIGNMENT 5

CSE2003-Data Structures and Algorithms

Winter Semester 2022-23

NAME: SOHIL SHETH


REG. NO.: 20BML0010

1. Write a program to Minimize the total length of wire connecting the customers
from src(0) node to central(dest [4]) by using the prim’s algorithm.

Algorithm:
 Create a set called mstSet that records the vertices that are already part of MST.
 Give each vertex in the input graph a key value. Make all key values initialised to
INFINITE. To ensure that the initial vertex is chosen, give it a key value of 0.
 While not all vertices are present in mstSet. Choose a vertex u with a minimum
key value that is absent from mstSet.
 Add u to the mstSet.
 Update the key value for each of u's neighbouring vertices. Iterate over all nearby
vertices to update the key values.
 Update the key value as the weight of edge u-v for each neighbouring vertex v if
the weight of edge u-v is less than the previous key value of v.
Code:

#include <iostream>
#include <vector>
#include <queue>
#include <climits>

using namespace std;


Name: Sohil Sheth
Reg. No: 20BML0010

const int INF = INT_MAX;

int main() {
cout<<"Starting"<<endl;
int n = 9;

vector<vector<pair<int, int> > > edges(n);

// Add edges
edges[0].push_back({1, 4});
edges[0].push_back({7, 8});
edges[1].push_back({2, 8});
edges[1].push_back({7, 11});
edges[2].push_back({3, 7});
edges[2].push_back({5, 4});
edges[2].push_back({8, 2});
edges[3].push_back({4, 9});
edges[3].push_back({5, 14});
edges[3].push_back({2, 7});
edges[4].push_back({3, 9});
edges[4].push_back({5, 10});
edges[5].push_back({2, 4});
edges[5].push_back({3, 14});
edges[5].push_back({4, 10});
edges[5].push_back({6, 2});
edges[6].push_back({5, 2});
edges[6].push_back({7, 1});
edges[6].push_back({8, 6});
edges[7].push_back({0, 8});
edges[7].push_back({1, 11});
edges[7].push_back({6, 1});
edges[7].push_back({8, 7});
edges[8].push_back({2, 2});
edges[8].push_back({6, 6});
edges[8].push_back({7, 7});

int src = 0;
int dest = 4;

priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq;

vector<int> key(n, INF);


vector<int> parent(n, -1);
vector<bool> inMST(n, false);

pq.push({0, src});
key[src] = 0;

while (!pq.empty()) {
Name: Sohil Sheth
Reg. No: 20BML0010

int u = pq.top().second;
pq.pop();

// Add the node to the minimum spanning tree


inMST[u] = true;
for (auto v : edges[u]) {
if (!inMST[v. irst] && v.second < key[v. irst]) {
key[v. irst] = v.second;
parent[v. irst] = u;
pq.push({key[v. irst], v. irst});
}
}
}

cout << "Minimum spanning tree:" << endl;


for (int i = 1; i < n; i++) {
cout << parent[i] << " - " << i << endl;
}

int total_length = 0;
for (int i = 1; i < n; i++) {
total_length += key[i];
}

// Print the total length of wire


cout << "Total length of wire: " << total_length << endl;

return 0;
}

Output:
Name: Sohil Sheth
Reg. No: 20BML0010

2. Write a program to find the shortest time path from vertex A to vertex H by using
Dijkstra's Algorithm. Consider the following graph, the vertices may be intersections,
and the edges may be roads.

Algorithm:

 First, we will mark all vertex as unvisited vertex.


 Then, we will mark the source vertex as 0 and all other vertices as infinity.
 Consider source vertex as current vertex.
 Calculate the path length of all the neighbouring vertex from the current vertex
by adding the weight of the edge in the current vertex.
 Now, if the new path length is smaller than the previous path length then replace
it otherwise ignore it
 Mark the current vertex as visited after visiting the neighbour vertex of the
current vertex.
 Select the vertex with the smallest path length as the new current vertex and go
back to step 4.
 Repeat this process until all the vertex are marked as visited.

Code:
#include <iostream>
#include <vector>
#include <queue>
#include <limits>

using namespace std;

typedef pair<int, int> pii;


typedef vector<vector<pii> > Graph;

const int INF = numeric_limits<int>::max();

int dijkstra(Graph& graph, int src, int dest) {


int N = graph.size();
Name: Sohil Sheth
Reg. No: 20BML0010

vector<bool> visited(N, false);


vector<int> dist(N, INF);
dist[src] = 0;
priority_queue<pii, vector<pii>, greater<pii> > pq;
pq.push(make_pair(0, src));
while (!pq.empty()) {
pii curr = pq.top(); pq.pop();
int node = curr.second, d = curr. irst;
if (visited[node]) continue;
visited[node] = true;
if (node == dest) return dist[dest];
for (auto& edge : graph[node]) {
int neighbor = edge. irst, weight = edge.second;
if (!visited[neighbor] && dist[node] + weight < dist[neighbor]) {
dist[neighbor] = dist[node] + weight;
pq.push(make_pair(dist[neighbor], neighbor));
}
}
}
return -1;
}

int main() {
Graph graph = {
{{1, 5}, {2, 7}}, // vertex A
{{0, 5}, {2, 10}, {3, 4}, {6, 17}}, // vertex B
{{0, 7}, {1, 10}, {3, 3}, {4, 15}}, // vertex C
{{1, 4}, {2, 3}, {4, 1}}, // vertex D
{{2, 15}, {3, 1}, {5, 3}}, // vertex E
{{4, 3}, {6, 2}}, // vertex F
{{1, 17}, {5, 2}, {7, 15}, {8, 4}}, // vertex G
{{6, 15}, {8, 2}}, // vertex H
{{6, 4}, {7, 2}} // vertex I
};
int shortest_time = dijkstra(graph, 0, 7);
if (shortest_time == -1) {
cout << "There is no path from A to H" << endl;
} else {
cout<<endl;
cout << "The shortest time path for the given undirected graph from A to H is: " <<
shortest_time << endl;
cout<<endl;
}
return 0;
}
Name: Sohil Sheth
Reg. No: 20BML0010

Output:

3. Write a program to implement selection sort on a given array.

Algorithm:
 Set the position 0 of the minimal value (min idx).
 Get the array's smallest element by traversing it.
 If an element smaller than min idx is discovered when traversing, then swap both
values.
 After that, increase min idx to point at the next element.
 Continue until the array has been sorted.
Code:
#include <iostream>
using namespace std;

void selectionSort(int arr[], int n)


{
int i, j, min_idx;

// One by one move boundary of unsorted subarray


for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

// Swap the found minimum element with the irst element


swap(arr[min_idx], arr[i]);
}
}

int main()
{
int arr[] = {12, 1, 22, 15, 11};
int n = sizeof(arr)/sizeof(arr[0]);
cout<<"Unsorted array:"<<endl;
cout<<"12 1 22 15 11"<<endl;
selectionSort(arr, n);
Name: Sohil Sheth
Reg. No: 20BML0010

cout << "Sorted array: \n";


for (int i=0; i < n; i++)
cout << arr[i] << " ";

return 0;
}

Output:

4. Write a program implement BFS traversal

Algorithm:
 Create a queue, then insert the irst vertex.
 Create a visited array from scratch and designate the irst vertex as visited.
 Till the line is empty, proceed as follows:
 Delete the queue's leading vertex.
 Vertex visited will be noted.
 Add all of the vertex's unvisited neighbours to the queue.

Pseudo code:
Breadth_First_Search( Graph, X ) // Here, Graph is the graph that we already have and X is the source node
Let Q be the queue
Q.enqueue( X ) // Inserting source node X into the queue
Mark X node as visited.
While ( Q is not empty )
Y = Q.dequeue( ) // Removing the front node from the queue
Process all the neighbors of Y, For all the neighbors Z of Y
If Z is not visited, Q. enqueue( Z ) // Stores Z in Q
Mark Z as visited
Name: Sohil Sheth
Reg. No: 20BML0010

Code:
#include <bits/stdc++.h>
using namespace std;

// This class represents a directed graph using


// adjacency list representation
class Graph {
int V; // No. of vertices
vector<list<int> > adj;

public:
Graph(int V); // Constructor

void addEdge(int v, int w);

void BFS(int s);


};

Graph::Graph(int V)
{
this->V = V;
adj.resize(V);
}

void Graph::addEdge(int v, int w)


{
adj[v].push_back(w); // Add w to v’s list.
}

void Graph::BFS(int s)
{
vector<bool> visited;
visited.resize(V, false);

list<int> queue;

visited[s] = true;
queue.push_back(s);

while (!queue.empty()) {
// Dequeue a vertex from queue and print it
s = queue.front();
cout << s << " ";
queue.pop_front();

// Get all adjacent vertices of the dequeued


// vertex s. If a adjacent has not been visited,
// then mark it visited and enqueue it
for (auto adjacent : adj[s]) {
Name: Sohil Sheth
Reg. No: 20BML0010

if (!visited[adjacent]) {
visited[adjacent] = true;
queue.push_back(adjacent);
}
}
}
}

int main()
{
// Create a graph given in the above diagram
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

cout << "Following is Breadth First Traversal "


<< "(starting from vertex 2) \n";
g.BFS(2);
return 0;
}

Output:

You might also like