0% found this document useful (0 votes)
17 views35 pages

Dsa Lab File Exp 15 DSF Till Further

The document contains implementations of various graph algorithms including Breadth-First Search (BFS), Depth-First Search (DFS), Prim's and Kruskal's algorithms for Minimum Spanning Tree (MST), and Dijkstra's and Floyd-Warshall algorithms for shortest paths. Each section provides code examples in C for creating graphs, adding edges, and executing the respective algorithms. The document serves as a practical guide for understanding and implementing fundamental graph algorithms.

Uploaded by

2k22.cse.2213341
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)
17 views35 pages

Dsa Lab File Exp 15 DSF Till Further

The document contains implementations of various graph algorithms including Breadth-First Search (BFS), Depth-First Search (DFS), Prim's and Kruskal's algorithms for Minimum Spanning Tree (MST), and Dijkstra's and Floyd-Warshall algorithms for shortest paths. Each section provides code examples in C for creating graphs, adding edges, and executing the respective algorithms. The document serves as a practical guide for understanding and implementing fundamental graph algorithms.

Uploaded by

2k22.cse.2213341
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/ 35

Experiment 15

Implimenting Bfs using graph


#include <stdio.h>

#include <stdlib.h> S Z

// Structure to represent a node in the adjacency list

struct Node {

int vertex;

struct Node* next;

};

// Structure to represent the adjacency list for each vertex

struct AdjList {

struct Node* head;

};

// Structure to represent the graph

struct Graph {

int vertices;

struct AdjList* array;

};

// Function to create a new node

struct Node* createNode(int vertex) {

struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

newNode->vertex = vertex;

newNode->next = NULL;

return newNode;

}
// Function to create a graph with a given number of vertices

struct Graph* createGraph(int vertices) {

struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));

graph->vertices = vertices;

graph->array = (struct AdjList*)malloc(vertices * sizeof(struct AdjList));

for (int i = 0; i < vertices; ++i)

graph->array[i].head = NULL;

return graph;

// Function to add an edge to the graph

void addEdge(struct Graph* graph, int src, int dest) {

// Add an edge from src to dest

struct Node* newNode = createNode(dest);

newNode->next = graph->array[src].head;

graph->array[src].head = newNode;

// Uncomment the following lines to make the graph undirected

/*

newNode = createNode(src);

newNode->next = graph->array[dest].head;

graph->array[dest].head = newNode;

*/

// Function to perform Breadth-First Search on the graph

void BFS(struct Graph* graph, int startVertex) {

// Create an array to keep track of visited vertices


int* visited = (int*)malloc(graph->vertices * sizeof(int));

for (int i = 0; i < graph->vertices; ++i)

visited[i] = 0;

// Create a queue for BFS

int queue[graph->vertices];

int front = -1, rear = -1;

// Enqueue the starting vertex and mark it as visited

queue[++rear] = startVertex;

visited[startVertex] = 1;

while (front < rear) {

// Dequeue a vertex and print it

int currentVertex = queue[++front];

printf("%d ", currentVertex);

// Traverse all adjacent vertices of the dequeued vertex

struct Node* temp = graph->array[currentVertex].head;

while (temp) {

int adjacentVertex = temp->vertex;

if (!visited[adjacentVertex]) {

// Enqueue the adjacent vertex and mark it as visited

queue[++rear] = adjacentVertex;

visited[adjacentVertex] = 1;

temp = temp->next;

free(visited);
}

// Driver program

int main() {

int vertices, edges;

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

scanf("%d", &vertices);

struct Graph* graph = createGraph(vertices);

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

scanf("%d", &edges);

printf("Enter the edges (source destination):\n");

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

int src, dest;

scanf("%d %d", &src, &dest);

addEdge(graph, src, dest);

int startVertex;

printf("Enter the starting vertex for BFS: ");

scanf("%d", &startVertex);

printf("Breadth-First Search starting from vertex %d: ", startVertex);

BFS(graph, startVertex);

return 0;

}
Impimenting dfs using graph

#include <stdio.h>

#include <stdlib.h>

#define MAX_VERTICES 100

struct Node {

int data;

struct Node* next;

};

struct Graph {

int numVertices;

struct Node* adjList[MAX_VERTICES];

int visited[MAX_VERTICES];

};

// Function to create a new node

struct Node* createNode(int data) {

struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));


newNode->data = data;

newNode->next = NULL;

return newNode;

// Function to create a graph

struct Graph* createGraph(int vertices) {

struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));

graph->numVertices = vertices;

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

graph->adjList[i] = NULL;

graph->visited[i] = 0;

return graph;

// Function to add an edge to the graph

void addEdge(struct Graph* graph, int src, int dest) {

struct Node* newNode = createNode(dest);

newNode->next = graph->adjList[src];

graph->adjList[src] = newNode;

// For undirected graph, add an edge from dest to src as well

newNode = createNode(src);

newNode->next = graph->adjList[dest];

graph->adjList[dest] = newNode;

// Function for Depth First Search


void DFS(struct Graph* graph, int vertex) {

struct Node* temp = graph->adjList[vertex];

graph->visited[vertex] = 1;

printf("%d ", vertex);

while (temp != NULL) {

int adjVertex = temp->data;

if (graph->visited[adjVertex] == 0) {

DFS(graph, adjVertex);

temp = temp->next;

int main() {

// Example usage

struct Graph* graph = createGraph(5);

addEdge(graph, 0, 1);

addEdge(graph, 0, 2);

addEdge(graph, 1, 3);

addEdge(graph, 2, 4);

printf("Depth First Search starting from vertex 0:\n");

DFS(graph, 0);

return 0;

}
Experiment 16 prims kruskal's MST
#include <stdio.h>

#include <stdlib.h>

#include <limits.h>

#define MAX_VERTICES 100

// Structure to represent an edge in the graph

struct Edge {

int src, dest, weight;

};

// Structure to represent a graph

struct Graph {

int numVertices;

int adjMatrix[MAX_VERTICES][MAX_VERTICES];

};
// Function to create a new graph

struct Graph* createGraph(int vertices) {

struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));

graph->numVertices = vertices;

// Initialize the adjacency matrix

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

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

graph->adjMatrix[i][j] = 0;

return graph;

// Function to add an edge to the graph

void addEdge(struct Graph* graph, int src, int dest, int weight) {

graph->adjMatrix[src][dest] = weight;

graph->adjMatrix[dest][src] = weight;

// Function to find the minimum key value vertex

int minKey(int key[], int mstSet[], int vertices) {

int min = INT_MAX, minIndex;

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

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

min = key[v];

minIndex = v;

}
}

return minIndex;

// Function to print the MST using Prim's algorithm

void printMSTPrim(struct Graph* graph, int parent[]) {

printf("Minimum Spanning Tree using Prim's Algorithm:\n");

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

printf("Edge: %d - %d, Weight: %d\n", parent[i], i, graph->adjMatrix[i][parent[i]]);

// Function to perform Prim's algorithm to find MST

void primMST(struct Graph* graph) {

int parent[MAX_VERTICES];

int key[MAX_VERTICES];

int mstSet[MAX_VERTICES];

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

key[i] = INT_MAX;

mstSet[i] = 0;

key[0] = 0;

parent[0] = -1;

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

int u = minKey(key, mstSet, graph->numVertices);

mstSet[u] = 1;
for (int v = 0; v < graph->numVertices; v++) {

if (graph->adjMatrix[u][v] && mstSet[v] == 0 && graph->adjMatrix[u][v] < key[v]) {

parent[v] = u;

key[v] = graph->adjMatrix[u][v];

printMSTPrim(graph, parent);

// Function to find the parent of a set

int find(int parent[], int i) {

if (parent[i] == -1)

return i;

return find(parent, parent[i]);

// Function to perform union of two sets

void unionSets(int parent[], int x, int y) {

int xSet = find(parent, x);

int ySet = find(parent, y);

parent[xSet] = ySet;

// Function to compare two edges based on their weights

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

return ((struct Edge*)a)->weight - ((struct Edge*)b)->weight;

// Function to print the MST using Kruskal's algorithm


void printMSTKruskal(struct Edge result[], int e) {

printf("Minimum Spanning Tree using Kruskal's Algorithm:\n");

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

printf("Edge: %d - %d, Weight: %d\n", result[i].src, result[i].dest, result[i].weight);

// Function to perform Kruskal's algorithm to find MST

void kruskalMST(struct Graph* graph) {

int v = graph->numVertices;

struct Edge result[v];

int e = 0;

int i = 0;

// Sort all the edges in non-decreasing order of their weight

struct Edge edges[v * v];

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

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

if (graph->adjMatrix[row][col] != 0) {

edges[i].src = row;

edges[i].dest = col;

edges[i].weight = graph->adjMatrix[row][col];

i++;

qsort(edges, i, sizeof(edges[0]), compareEdges);

// Allocate memory for parent array

int parent[v];
for (int j = 0; j < v; j++) {

parent[j] = -1;

i = 0; // Index used to pick the next edge

while (e < v - 1 && i < graph->numVertices * graph->numVertices) {

struct Edge nextEdge = edges[i++];

int x = find(parent, nextEdge.src);

int y = find(parent, nextEdge.dest);

if (x != y) {

result[e++] = nextEdge;

unionSets(parent, x, y);

printMSTKruskal(result, e);

int main() {

// Example usage

int vertices = 4;

struct Graph* graph = createGraph(vertices);

// Add edges with weights to the graph

addEdge(graph, 0, 1, 10);

addEdge(graph, 0, 2, 6);

addEdge(graph, 0, 3, 5);

addEdge(graph, 1, 3, 15);

addEdge(graph, 2, 3, 4);
// Find and print Minimum Spanning Tree using Prim's algorithm

primMST(graph);

// Find and print Minimum Spanning Tree using Kruskal's algorithm

kruskalMST(graph);

return 0;

}
Experiment 17
Implementing shortest path algorithms to
compare single source shortest path and all pairs
shortest path
#include <stdio.h>

#include <limits.h>

#define V 4 // Number of vertices

// Function to find the vertex with the minimum distance value,

// from the set of vertices not yet included in the shortest path tree

int minDistance(int dist[], int sptSet[]) {

int min = INT_MAX, min_index;

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

if (sptSet[v] == 0 && dist[v] <= min) {

min = dist[v];

min_index = v;

return min_index;

// Function to print the final solution

void printSolution(int dist[], int n) {

printf("Vertex Distance from Source\n");


for (int i = 0; i < n; i++)

printf("%d \t\t %d\n", i, dist[i]);

// Function that implements Dijkstra's single source shortest path algorithm

void dijkstra(int graph[V][V], int src) {

int dist[V]; // The output array dist[i] holds the shortest distance from src to i

int sptSet[V]; // sptSet[i] will be true if vertex i is included in the shortest path tree or the shortest
distance from src to i is finalized

// Initialize all distances as INFINITE and sptSet[] as false

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

dist[i] = INT_MAX;

sptSet[i] = 0;

// Distance of source vertex from itself is always 0

dist[src] = 0;

// Find the shortest path for all vertices

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

// Pick the minimum distance vertex from the set of vertices not yet processed.

int u = minDistance(dist, sptSet);

// Mark the picked vertex as processed

sptSet[u] = 1;

// Update dist[] value of the adjacent vertices of the picked vertex.

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

// Update dist[v] only if it is not in the sptSet, there is an edge from u to v,

// and the total weight of path from src to v through u is less than the current value of dist[v]
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v])

dist[v] = dist[u] + graph[u][v];

// Print the constructed distance array

printSolution(dist, V);

// Function to implement Floyd-Warshall algorithm for all pairs shortest path

void floydWarshall(int graph[V][V]) {

int dist[V][V];

// Initialize the solution matrix same as input graph matrix

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

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

dist[i][j] = graph[i][j];

// Update dist[][] with all vertices as intermediate vertices

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

// Pick all vertices as source one by one

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

// Pick all vertices as destination for the above picked source

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

// If vertex k is on the shortest path from i to j,

// then update the value of dist[i][j]

if (dist[i][k] != INT_MAX && dist[k][j] != INT_MAX &&

dist[i][k] + dist[k][j] < dist[i][j])

dist[i][j] = dist[i][k] + dist[k][j];

}
}

// Print the shortest distance matrix

printf("\n\nAll Pairs Shortest Paths:\n");

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

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

if (dist[i][j] == INT_MAX)

printf("INF\t");

else

printf("%d\t", dist[i][j]);

printf("\n");

int main() {

// Example graph represented as an adjacency matrix

int graph[V][V] = {{0, 2, INT_MAX, 1},

{INT_MAX, 0, 3, INT_MAX},

{INT_MAX, INT_MAX, 0, 4},

{INT_MAX, INT_MAX, INT_MAX, 0}};

// Example usage of Dijkstra's algorithm

printf("Single Source Shortest Path:\n");

dijkstra(graph, 0);

// Example usage of Floyd-Warshall algorithm

floydWarshall(graph);

return 0;

}
Experiment 18
Implementing traversal in threaded binary system
#include <stdio.h>

#include <stdlib.h>

// Node structure for threaded binary tree

struct Node {

int data;

struct Node* left;

struct Node* right;

int isThreaded; // Flag to indicate if the right pointer is a thread

};

// Function to create a new threaded binary tree node

struct Node* createNode(int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

if (newNode == NULL) {

printf("Memory allocation failed\n");

exit(EXIT_FAILURE);

newNode->data = data;

newNode->left = NULL;

newNode->right = NULL;

newNode->isThreaded = 0; // Initially, set the right pointer as NULL (not threaded)

return newNode;

// Function to perform inorder threading of a binary tree

void threadedInorder(struct Node* root, struct Node** prev) {

if (root) {

// Recur on the left subtree

threadedInorder(root->left, prev);

// Thread the current node

if (*prev && (*prev)->right == NULL) {

(*prev)->right = root;

(*prev)->isThreaded = 1;

// Update the previous pointer

*prev = root;

// Recur on the right subtree or follow the thread

if (!root->isThreaded) {
threadedInorder(root->right, prev);

// Function to perform threaded inorder traversal

void threadedInorderTraversal(struct Node* root) {

struct Node* current = root;

while (current) {

// Find the leftmost node in the current subtree

while (current->left) {

current = current->left;

// Process the current node

printf("%d ", current->data);

// Follow the thread to the next node in inorder

while (current->isThreaded) {

current = current->right;

printf("%d ", current->data);

// Move to the right subtree

current = current->right;

// Driver program

int main() {
// Construct a threaded binary tree

struct Node* root = createNode(1);

root->left = createNode(2);

root->right = createNode(3);

root->left->left = createNode(4);

root->left->right = createNode(5);

root->right->left = createNode(6);

root->right->right = createNode(7);

// Perform inorder threading

struct Node* prev = NULL;

threadedInorder(root, &prev);

// Perform threaded inorder traversal

printf("Threaded Inorder Traversal: ");

threadedInorderTraversal(root);

printf("\n");

printf(" Tejas Kushwaha \n 2201640100358");

return 0;

}
Experiment 19
Implimenting huffman coding using
binary tree
// C program for Huffman Coding
#include <stdio.h>
#include <stdlib.h>

#define MAX_TREE_HT 100

struct MinHeapNode {

char data;

unsigned freq;

struct MinHeapNode *left, *right;


};

struct MinHeap {

unsigned size;
unsigned capacity;

struct MinHeapNode** array;


};

struct MinHeapNode* newNode(char data, unsigned freq)


{
struct MinHeapNode* temp = (struct MinHeapNode*)malloc(
sizeof(struct MinHeapNode));

temp->left = temp->right = NULL;


temp->data = data;
temp->freq = freq;

return temp;
}

struct MinHeap* createMinHeap(unsigned capacity)

struct MinHeap* minHeap


= (struct MinHeap*)malloc(sizeof(struct MinHeap));

minHeap->size = 0;
minHeap->capacity = capacity;

minHeap->array = (struct MinHeapNode**)malloc(


minHeap->capacity * sizeof(struct MinHeapNode*));
return minHeap;
}

void swapMinHeapNode(struct MinHeapNode** a,


struct MinHeapNode** b)

struct MinHeapNode* t = *a;


*a = *b;
*b = t;
}

void minHeapify(struct MinHeap* minHeap, int idx)

int smallest = idx;


int left = 2 * idx + 1;
int right = 2 * idx + 2;

if (left < minHeap->size


&& minHeap->array[left]->freq
< minHeap->array[smallest]->freq)
smallest = left;

if (right < minHeap->size


&& minHeap->array[right]->freq
< minHeap->array[smallest]->freq)
smallest = right;

if (smallest != idx) {
swapMinHeapNode(&minHeap->array[smallest],
&minHeap->array[idx]);
minHeapify(minHeap, smallest);
}
}

int isSizeOne(struct MinHeap* minHeap)


{

return (minHeap->size == 1);


}

struct MinHeapNode* extractMin(struct MinHeap* minHeap)

{
struct MinHeapNode* temp = minHeap->array[0];
minHeap->array[0] = minHeap->array[minHeap->size - 1];

--minHeap->size;
minHeapify(minHeap, 0);

return temp;
}

void insertMinHeap(struct MinHeap* minHeap,


struct MinHeapNode* minHeapNode)

++minHeap->size;
int i = minHeap->size - 1;

while (i
&& minHeapNode->freq
< minHeap->array[(i - 1) / 2]->freq) {

minHeap->array[i] = minHeap->array[(i - 1) / 2];


i = (i - 1) / 2;
}

minHeap->array[i] = minHeapNode;
}

void buildMinHeap(struct MinHeap* minHeap)

int n = minHeap->size - 1;
int i;

for (i = (n - 1) / 2; i >= 0; --i)


minHeapify(minHeap, i);
}

void printArr(int arr[], int n)


{
int i;
for (i = 0; i < n; ++i)
printf("%d", arr[i]);

printf("\n");
}

int isLeaf(struct MinHeapNode* root)

{
return !(root->left) && !(root->right);
}

struct MinHeap* createAndBuildMinHeap(char data[],


int freq[], int size)

struct MinHeap* minHeap = createMinHeap(size);

for (int i = 0; i < size; ++i)


minHeap->array[i] = newNode(data[i], freq[i]);

minHeap->size = size;
buildMinHeap(minHeap);

return minHeap;
}

struct MinHeapNode* buildHuffmanTree(char data[],


int freq[], int size)

{
struct MinHeapNode *left, *right, *top;
struct MinHeap* minHeap
= createAndBuildMinHeap(data, freq, size);

while (!isSizeOne(minHeap)) {

left = extractMin(minHeap);
right = extractMin(minHeap);

top = newNode('$', left->freq + right->freq);

top->left = left;
top->right = right;

insertMinHeap(minHeap, top);
}

return extractMin(minHeap);
}

void printCodes(struct MinHeapNode* root, int arr[],


int top)
{

if (root->left) {

arr[top] = 0;
printCodes(root->left, arr, top + 1);
}

if (root->right) {

arr[top] = 1;
printCodes(root->right, arr, top + 1);
}

if (isLeaf(root)) {

printf("%c: ", root->data);


printArr(arr, top);
}
}

void HuffmanCodes(char data[], int freq[], int size)

{
struct MinHeapNode* root
= buildHuffmanTree(data, freq, size);

int arr[MAX_TREE_HT], top = 0;

printCodes(root, arr, top);


}

int main()
{
printf ("huffman codeing using binary tree ");

char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' };


int freq[] = { 5, 9, 12, 13, 16, 45 };

int size = sizeof(arr) / sizeof(arr[0]);

HuffmanCodes(arr, freq, size);


printf(" \n Tejas Kushwaha \n 2201640100358");

return 0;
}
Experiment 20
Implimenting hanaoi tree using recurssion to
compare interactive and recursive methods
#include <stdio.h>

// Recursive function to solve Tower of Hanoi problem

void hanoiRecursive(int n, char source, char auxiliary, char destination) {

if (n == 1) {

printf("Move disk 1 from %c to %c\n", source, destination);

return;

}
hanoiRecursive(n - 1, source, destination, auxiliary);

printf("Move disk %d from %c to %c\n", n, source, destination);

hanoiRecursive(n - 1, auxiliary, source, destination);

// Interactive function to solve Tower of Hanoi problem step by step

void hanoiInteractive(int n, char source, char auxiliary, char destination) {

int move;

printf("Enter the number of moves to execute: ");

scanf("%d", &move);

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

printf("Move %d:\n", i + 1);

hanoiRecursive(n, source, auxiliary, destination);

int main() {

int n;

char source = 'A', auxiliary = 'B', destination = 'C';

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

scanf("%d", &n);

// Recursive method

printf("\nRecursive method:\n");

hanoiRecursive(n, source, auxiliary, destination);

// Interactive method

printf("\nInteractive method:\n");

hanoiInteractive(n, source, auxiliary, destination);


printf("\nTejas kushwaha \n 2201640100358");

return 0;

You might also like