0% found this document useful (0 votes)
25 views15 pages

Assign 5

The document contains implementations of three graph algorithms: Topological Sort using Kahn's Algorithm, Prim's Algorithm for Minimum Spanning Tree (MST), and Kruskal's Algorithm for MST. Each algorithm is accompanied by C code that includes functions for initializing data structures, processing input, and displaying results. The examples demonstrate how to input graph data and obtain the desired outputs for each algorithm.

Uploaded by

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

Assign 5

The document contains implementations of three graph algorithms: Topological Sort using Kahn's Algorithm, Prim's Algorithm for Minimum Spanning Tree (MST), and Kruskal's Algorithm for MST. Each algorithm is accompanied by C code that includes functions for initializing data structures, processing input, and displaying results. The examples demonstrate how to input graph data and obtain the desired outputs for each algorithm.

Uploaded by

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

Topological sort

#include <stdio.h>

#include <stdlib.h>

#define MAX 100

typedef struct {

int items[MAX];

int front, rear;

} Queue;

void initQueue(Queue* q) {

q->front = 0;

q->rear = -1;

int isQueueEmpty(Queue* q) {

return q->front > q->rear;

void enqueue(Queue* q, int value) {

if (q->rear < MAX - 1) {

q->items[++q->rear] = value;

}
int dequeue(Queue* q) {

if (!isQueueEmpty(q)) {

return q->items[q->front++];

return -1;

// Topological Sort using Kahn's Algorithm

void topologicalSort(int graph[MAX][MAX], int numVertices) {

int inDegree[MAX] = {0};

Queue q;

initQueue(&q);

// Calculate in-degree of all vertices

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

for (int j = 0; j < numVertices; j++) {

if (graph[j][i]) {

inDegree[i]++;

// Enqueue all vertices with in-degree 0

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

if (inDegree[i] == 0) {

enqueue(&q, i);
}

// Perform topological sort

int count = 0;

int topOrder[MAX];

while (!isQueueEmpty(&q)) {

int current = dequeue(&q);

topOrder[count++] = current;

// Reduce the in-degree of adjacent vertices

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

if (graph[current][i]) {

inDegree[i]--;

if (inDegree[i] == 0) {

enqueue(&q, i);

// Check if there was a cycle

if (count != numVertices) {

printf("The graph contains a cycle. Topological sorting is not possible.\n");

return;
}

// Print topological order

printf("Topological Sort: ");

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

printf("%d ", topOrder[i]);

printf("\n");

int main() {

int numVertices;

int graph[MAX][MAX];

// Input the number of vertices

printf("Enter the number of vertices: ");

scanf("%d", &numVertices);

// Input the adjacency matrix

printf("Enter the adjacency matrix (use 0 for no edge):\n");

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

for (int j = 0; j < numVertices; j++) {

scanf("%d", &graph[i][j]);

}
// Perform Topological Sort

topologicalSort(graph, numVertices);

return 0;

Enter the number of vertices: 6

Enter the adjacency matrix (use 0 for no edge):

011000

000110

000001

000000

000001

000000

Topological Sort: 0 2 5 1 4 3
2.prims

#include <stdio.h>

#include <stdbool.h>

#define MAX 100

#define INF 99999

// Function to find the vertex with the minimum key value that is not yet included in MST

int findMinVertex(int key[], bool mstSet[], int n) {

int min = INF, minIndex;

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

if (!mstSet[v] && key[v] < min) {

min = key[v];

minIndex = v;
}

return minIndex;

// Function to implement Prim's Algorithm

void prims(int graph[MAX][MAX], int numVertices) {

int parent[MAX]; // Array to store the MST

int key[MAX]; // Array to store the minimum weight edge

bool mstSet[MAX]; // To track vertices included in MST

// Initialize all keys as infinite and mstSet[] as false

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

key[i] = INF;

mstSet[i] = false;

// Start with the first vertex

key[0] = 0; // Make key value of the first vertex 0

parent[0] = -1; // First vertex is the root of the MST

// Build the MST

for (int count = 0; count < numVertices - 1; count++) {

// Pick the vertex with the smallest key value


int u = findMinVertex(key, mstSet, numVertices);

// Add the picked vertex to the MST set

mstSet[u] = true;

// Update key values and parent indices of adjacent vertices

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

// Update key[v] if graph[u][v] is smaller, and v is not in mstSet

if (graph[u][v] && !mstSet[v] && graph[u][v] < key[v]) {

parent[v] = u;

key[v] = graph[u][v];

// Print the MST

printf("Edge \tWeight\n");

for (int i = 1; i < numVertices; i++) {

printf("%d - %d \t%d\n", parent[i], i, graph[i][parent[i]]);

int main() {

int numVertices;
int graph[MAX][MAX];

// Input number of vertices

printf("Enter the number of vertices: ");

scanf("%d", &numVertices);

// Input graph as adjacency matrix

printf("Enter the adjacency matrix of the graph:\n");

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

for (int j = 0; j < numVertices; j++) {

scanf("%d", &graph[i][j]);

// Run Prim's Algorithm

prims(graph, numVertices);

return 0;

Enter the number of vertices: 5

Enter the adjacency matrix of the graph:

02060

20385

03007
68009

05790

Edge Weight

0-1 2

1-2 3

0-3 6

1-4 5
3.Kruskals

#include <stdio.h>

#include <stdlib.h>

#define MAX 100

// Structure to represent an edge

typedef struct {

int u, v, weight;

} Edge;

Edge edges[MAX];

Edge mst[MAX];

int parent[MAX];

int numEdges, numVertices;

// Function to find the parent of a vertex (with path compression)

int find(int v) {

if (parent[v] != v) {

parent[v] = find(parent[v]);

return parent[v];

}
// Function to perform union of two subsets

void unionSets(int u, int v) {

int rootU = find(u);

int rootV = find(v);

parent[rootU] = rootV;

// Comparison function for sorting edges by weight

int compareEdges(const void* a, const void* b) {

Edge* edgeA = (Edge*)a;

Edge* edgeB = (Edge*)b;

return edgeA->weight - edgeB->weight;

// Kruskal's Algorithm

void kruskal() {

int mstEdges = 0, mstWeight = 0;

// Sort all edges by weight

qsort(edges, numEdges, sizeof(Edge), compareEdges);

// Initialize disjoint sets

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

parent[i] = i;
}

// Iterate through all edges

for (int i = 0; i < numEdges && mstEdges < numVertices - 1; i++) {

int u = edges[i].u;

int v = edges[i].v;

int weight = edges[i].weight;

// Check if the edge forms a cycle

if (find(u) != find(v)) {

mst[mstEdges++] = edges[i]; // Add edge to MST

mstWeight += weight;

unionSets(u, v); // Union the sets

// Print the MST

printf("Edges in the Minimum Spanning Tree:\n");

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

printf("(%d, %d) -> %d\n", mst[i].u, mst[i].v, mst[i].weight);

printf("Total weight of MST: %d\n", mstWeight);

}
int main() {

printf("Enter the number of vertices: ");

scanf("%d", &numVertices);

printf("Enter the number of edges: ");

scanf("%d", &numEdges);

printf("Enter the edges (u, v, weight):\n");

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

scanf("%d %d %d", &edges[i].u, &edges[i].v, &edges[i].weight);

kruskal();

return 0;

Enter the number of vertices: 4

Enter the number of edges: 5

Enter the edges (u, v, weight):

0 1 10

026

035

1 3 15

234
Edges in the Minimum Spanning Tree:

(2, 3) -> 4

(0, 3) -> 5

(0, 1) -> 10

Total weight of MST: 19

You might also like