Shalini DAA assignment
Shalini DAA assignment
PCA-2 (P (PCC-CS494)
CSE – 4th Sem. – 2nd Year
Program:
#include <stdio.h>
#include <limits.h>
#define MAX_VERTICES 100
int main()
{
int V;
printf("\t\t\t ----# PRIM'S ALGORITHM #----\n");
printf("\nEnter the number of vertices: ");
scanf("%d", &V);
int graph[MAX_VERTICES][MAX_VERTICES];
printf("\nEnter the adjacency matrix of the graph: \n\n");
int i, j;
for (i = 0; i < V; i++)
{
printf("Enter row %d:\n", i + 1);
for (j = 0; j < V; j++)
{
scanf("%d", &graph[i][j]);
}
}
primMST(V, graph);
return 0;
}
Assignment No. – I Page - 1 SHALINI DAS, 23/CSE/023, </> CSE Dept, FIEM
Design Analysis & Algorithm Lab
PCA-2 (P (PCC-CS494)
CSE – 4th Sem. – 2nd Year
int count;
for (count = 0; count < V - 1; count++)
{
int u = minKey(key, mstSet, V), v;
mstSet[u] = 1;
for (v = 0; v < V; v++)
if (graph[u][v] && mstSet[v] == 0 && graph[u][v] < key[v])
parent[v] = u, key[v] = graph[u][v];
}
printMST(parent, V, graph);
}
Assignment No. – I Page - 2 SHALINI DAS, 23/CSE/023, </> CSE Dept, FIEM
Design Analysis & Algorithm Lab
PCA-2 (P (PCC-CS494)
CSE – 4th Sem. – 2nd Year
Output:
Enter row 1:
11 22 33 44
Enter row 2:
10 20 30 40
Enter row 3:
5
10 15 20
Enter row 4:
20 25 30 35
Edge Weight
0 - 1 10
1 - 2 10
2 - 3 30
Assignment No. – I Page - 3 SHALINI DAS, 23/CSE/023, </> CSE Dept, FIEM
Design Analysis & Algorithm Lab
PCA-2 (P (PCC-CS494)
CSE – 4th Sem. – 2nd Year
Program:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int src, dest, weight;
} Edge;
typedef struct {
int parent;
int rank;
} Subset;
Edge edges[MAX_EDGES];
Assignment No. – I Page - 4 SHALINI DAS, 23/CSE/023, </> CSE Dept, FIEM
Design Analysis & Algorithm Lab
PCA-2 (P (PCC-CS494)
CSE – 4th Sem. – 2nd Year
Edge result[MAX_VERTICES];
int e = 0, i = 0;
int totalWeight = 0;
if (E < V - 1) {
printf("\nError: Not enough edges to form a spanning tree.\n");
free(subsets);
return;
}
if (x != y) {
result[e++] = next_edge;
unionSets(subsets, x, y);
}
}
printf("\nEdge Weight\n");
for (i = 0; i < e; ++i) {
printf("%d - %d %d\n", result[i].src, result[i].dest, result[i].weight);
totalWeight += result[i].weight;
}
printf("\nTotal weight of MST is : %d\n", totalWeight);
free(subsets);
}
Assignment No. – I Page - 5 SHALINI DAS, 23/CSE/023, </> CSE Dept, FIEM
Design Analysis & Algorithm Lab
PCA-2 (P (PCC-CS494)
CSE – 4th Sem. – 2nd Year
int main() {
int V, E, i;
printf("\t\t\t ----# KRUSKAL'S ALGORITHM #----\n");
printf("\nEnter the number of vertices: ");
scanf("%d", &V);
printf("Enter the number of edges: ");
scanf("%d", &E);
kruskalMST(V, E);
return 0;
}
Output:
Edge 1: 1 2 10
Edge 2: 2 3 20
Edge 3: 3 4 30
Edge 4: 4 5 40
Edge Weight
1 - 2 10
2 - 3 20
3 - 4 30
--------------------------------
Process exited after 25.88 seconds with return value 0
Press any key to continue . . .
Assignment No. – I Page - 6 SHALINI DAS, 23/CSE/023, </> CSE Dept, FIEM