0% found this document useful (0 votes)
8 views

codetantra lab program DSA2

The document outlines a series of programming tasks for a Data Structure and Algorithm lab focused on binary trees and graph algorithms. It includes instructions for implementing various tree traversal methods (in-order, pre-order, post-order), as well as operations for binary search trees and graph algorithms like Dijkstra's and Prim's. Additionally, it provides example code and test cases for validating the implementations.

Uploaded by

solicad398
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

codetantra lab program DSA2

The document outlines a series of programming tasks for a Data Structure and Algorithm lab focused on binary trees and graph algorithms. It includes instructions for implementing various tree traversal methods (in-order, pre-order, post-order), as well as operations for binary search trees and graph algorithms like Dijkstra's and Prim's. Additionally, it provides example code and test cases for validating the implementations.

Uploaded by

solicad398
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 89

DATA STRUCTURE AND ALGORITHM LAB 2

IV/2nd YEAR/CSE

TO ADD NEW LAB


1. Write a program to implement an in-order traversal of a binary tree and print the nodes.
2. Write a program to implement a pre-order traversal of a binary tree and print the nodes.
3. Write a program to implement a post-order traversal of a binary tree and print the nodes.
4. Write a program to implement a menu-driven program for binary tree traversal (in-order,
pre-order, post-order) and searching.
5. Write a program to count the number of nodes in a binary tree.
6. Write a program to find the height of the tree.
7. Write a program to check if the binary tree is balanced or not.
8. Write a program to search a number in a Binary Search Tree (BST).
9. Write a program to insert a node in a Binary Search Tree (BST).
10. Write a program to delete a node from a Binary Search Tree (BST).
11. Write a program to implement insertion and search operations in a tree.
12. Write a program to calculate the balance factor of each node of the AVL tree.
13. Write a program to implement a max-heap and perform heap sort on an array of integers.
14. Write a program to implement a priority queue using a max heap.
15. Write a program to create a graph using an adjacency matrix.
16. Write a program to create a graph using an adjacency list.
17. Write a program to perform Depth-First Search (DFS) on a graph.
18. Write a program to perform Breadth-First Search (BFS) on a graph.
19. Write a program to check if there is a path between two nodes in a graph using DFS.
20. Write a program to find all the vertices reachable from a given vertex in a graph using
BFS.
21. Write a program to detect a cycle in an undirected graph using DFS.
22. Write a program to detect a cycle in a directed graph using DFS.
23. Write a program to find the degree of each vertex in an undirected graph.
24. Write a program to count the number of connected components in an undirected graph.
25. Write a program to implement Dijkstra's Algorithm.
26. Write a program to implement Prim's Algorithm.
27. Write a program to implement Kruskal's Algorithm.
28. Write a program to implement Floyd-Warshall's all-pair shortest path algorithm.
29. Write a program to implement Bellman-Ford Algorithm.
30. Write a program to implement Longest Common Subsequence (LCS).
31. Write a program to implement the sum of subset problem using backtracking.

LAB NUMBER/QUESTION NUMBER [AS MENTIONED IN CODETANTRA LAB]


Lab no. 1/S.NO.1&In-Order Traversal of a
Binary Tree
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
struct Node* constructTree() {
int data;
printf("Enter data for node (-1 for no node): ");
scanf("%d", &data);
if (data == -1)
return NULL;
struct Node* newNode = createNode(data);
printf("Enter left child of %d\n", data);
newNode->left = constructTree();
printf("Enter right child of %d\n", data);
newNode->right = constructTree();
return newNode;
}
void preorderTraversal(struct Node* root) {
if (root == NULL)
return;
printf("%d ", root->data);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
int main() {
struct Node* root = NULL;

printf("Construct the binary tree:\n");


root = constructTree();
printf("Pre-Order Traversal: ");
preorderTraversal(root);
printf("\n");
return 0;
}
OUTPUT

Test Case 1: Simple Binary Tree


Enter data for node (-1 for no node): 1
Enter left child of 1
Enter data for node (-1 for no node): 2
Enter left child of 2
Enter data for node (-1 for no node): -1
Enter right child of 2
Enter data for node (-1 for no node): -1
Enter right child of 1
Enter data for node (-1 for no node): 3
Enter left child of 3
Enter data for node (-1 for no node): -1
Enter right child of 3
Enter data for node (-1 for no node): -1
Expected Output:
Pre-Order Traversal: 1 2 3

Test Case 2: Larger Binary Tree


Enter data for node (-1 for no node): 10
Enter left child of 10
Enter data for node (-1 for no node): 5
Enter left child of 5
Enter data for node (-1 for no node): 2
Enter left child of 2
Enter data for node (-1 for no node): -1
Enter right child of 2
Enter data for node (-1 for no node): -1
Enter right child of 5
Enter data for node (-1 for no node): 7
Enter left child of 7
Enter data for node (-1 for no node): -1
Enter right child of 7
Enter data for node (-1 for no node): -1
Enter right child of 10
Enter data for node (-1 for no node): 15
Enter left child of 15
Enter data for node (-1 for no node): 12
Enter left child of 12
Enter data for node (-1 for no node): -1
Enter right child of 12
Enter data for node (-1 for no node): -1
Enter right child of 15
Enter data for node (-1 for no node): 20
Enter left child of 20
Enter data for node (-1 for no node): -1
Enter right child of 20
Enter data for node (-1 for no node): -1

Expected Output:
Pre-Order Traversal: 10 5 2 7 15 12 20

Test Case 3: Empty Tree


Enter data for node (-1 for no node): -1

Expected Output:
Pre-Order Traversal:

Lab no. 1/S.NO.2&Pre-Order Traversal of a


Binary Tree

#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
struct Node* constructTree() {
int data;
printf("Enter data for node (-1 for no node): ");
scanf("%d", &data);
if (data == -1)
return NULL;
struct Node* newNode = createNode(data);
printf("Enter left child of %d\n", data);
newNode->left = constructTree();
printf("Enter right child of %d\n", data);
newNode->right = constructTree();
return newNode;
}
void preorderTraversal(struct Node* root) {
if (root == NULL)
return;
printf("%d ", root->data);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
int main() {
struct Node* root = NULL;
printf("Construct the binary tree:\n");
root = constructTree();
printf("Pre-Order Traversal: ");
preorderTraversal(root);
printf("\n");
return 0;
}

Test Cases

Test Case 1: Full Binary Tree

Input:Construct the binary tree:


Enter data for node (-1 for no node): 1
Enter left child of 1
Enter data for node (-1 for no node): 2
Enter left child of 2
Enter data for node (-1 for no node): 4
Enter left child of 4
Enter data for node (-1 for no node): -1
Enter right child of 4
Enter data for node (-1 for no node): -1
Enter right child of 2
Enter data for node (-1 for no node): 5
Enter left child of 5
Enter data for node (-1 for no node): -1
Enter right child of 5
Enter data for node (-1 for no node): -1
Enter right child of 1
Enter data for node (-1 for no node): 3
Enter left child of 3
Enter data for node (-1 for no node): 6
Enter left child of 6
Enter data for node (-1 for no node): -1
Enter right child of 6
Enter data for node (-1 for no node): -1
Enter right child of 3
Enter data for node (-1 for no node): 7
Enter left child of 7
Enter data for node (-1 for no node): -1
Enter right child of 7
Enter data for node (-1 for no node): -1

Output:
Pre-Order Traversal: 1 2 4 5 3 6 7

Test Case 2: Skewed Tree (Left-heavy)

Input:
Construct the binary tree:
Enter data for node (-1 for no node): 1
Enter left child of 1
Enter data for node (-1 for no node): 2
Enter left child of 2
Enter data for node (-1 for no node): 3
Enter left child of 3
Enter data for node (-1 for no node): 4
Enter left child of 4
Enter data for node (-1 for no node): -1
Enter right child of 4
Enter data for node (-1 for no node): -1
Enter right child of 3
Enter data for node (-1 for no node): -1
Enter right child of 2
Enter data for node (-1 for no node): -1
Enter right child of 1
Enter data for node (-1 for no node): -1

Output:
Pre-Order Traversal: 1 2 3 4

Test Case 3: Skewed Tree (Right-heavy)


Input:
Construct the binary tree:
Enter data for node (-1 for no node): 1
Enter left child of 1
Enter data for node (-1 for no node): -1
Enter right child of 1
Enter data for node (-1 for no node): 2
Enter left child of 2
Enter data for node (-1 for no node): -1
Enter right child of 2
Enter data for node (-1 for no node): 3
Enter left child of 3
Enter data for node (-1 for no node): -1
Enter right child of 3
Enter data for node (-1 for no node): 4
Enter left child of 4
Enter data for node (-1 for no node): -1
Enter right child of 4
Enter data for node (-1 for no node): -1
Output:
Pre-Order Traversal: 1 2 3 4
Lab no. 1/S.NO.3&Post-Order Traversal of a
Binary Tree
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Function to create a new node
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
// Function to construct the tree by taking user input
struct Node* constructTree() {
int data;
printf("Enter data for node (-1 for no node): ");
scanf("%d", &data);
// If the user enters -1, return NULL (no node)
if (data == -1)
return NULL;
struct Node* newNode = createNode(data);
printf("Enter left child of %d\n", data);
newNode->left = constructTree();
printf("Enter right child of %d\n", data);
newNode->right = constructTree();

return newNode;
}
// Function for post-order traversal
void postorderTraversal(struct Node* root) {
if (root == NULL)
return;
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->data);
}
int main() {
struct Node* root = NULL;
// Build the tree with user input
printf("Construct the binary tree:\n");
root = constructTree();
// Perform post-order traversal
printf("Post-Order Traversal: ");
postorderTraversal(root);
printf("\n");
return 0;
}

Test Cases for the Binary Tree Program (Post-Order Traversal)

Test Case 1:

Input:
Enter data for node (-1 for no node): 1
Enter left child of 1
Enter data for node (-1 for no node): 2
Enter left child of 2
Enter data for node (-1 for no node): 4
Enter left child of 4
Enter data for node (-1 for no node): -1
Enter right child of 4
Enter data for node (-1 for no node): -1
Enter right child of 2
Enter data for node (-1 for no node): 5
Enter left child of 5
Enter data for node (-1 for no node): -1
Enter right child of 5
Enter data for node (-1 for no node): -1
Enter right child of 1
Enter data for node (-1 for no node): 3
Enter left child of 3
Enter data for node (-1 for no node): -1
Enter right child of 3
Enter data for node (-1 for no node): -1

Output:
Post-Order Traversal: 4 5 2 3 1

Test Case 2
Input:
Enter data for node (-1 for no node): 10
Enter left child of 10
Enter data for node (-1 for no node): 20
Enter left child of 20
Enter data for node (-1 for no node): 40
Enter left child of 40
Enter data for node (-1 for no node): -1
Enter right child of 40
Enter data for node (-1 for no node): -1
Enter right child of 20
Enter data for node (-1 for no node): 50
Enter left child of 50
Enter data for node (-1 for no node): -1
Enter right child of 50
Enter data for node (-1 for no node): -1
Enter right child of 10
Enter data for node (-1 for no node): 30
Enter left child of 30
Enter data for node (-1 for no node): 60
Enter left child of 60
Enter data for node (-1 for no node): -1
Enter right child of 60
Enter data for node (-1 for no node): -1
Enter right child of 30
Enter data for node (-1 for no node): 70
Enter left child of 70
Enter data for node (-1 for no node): -1
Enter right child of 70
Enter data for node (-1 for no node): -1

Output:
Post-Order Traversal: 40 50 20 60 70 30 10

Test Case 3:
Input:
Enter data for node (-1 for no node): 5
Enter left child of 5
Enter data for node (-1 for no node): 3
Enter left child of 3
Enter data for node (-1 for no node): -1
Enter right child of 3
Enter data for node (-1 for no node): 4
Enter left child of 4
Enter data for node (-1 for no node): -1
Enter right child of 4
Enter data for node (-1 for no node): -1
Enter right child of 5
Enter data for node (-1 for no node): 8
Enter left child of 8
Enter data for node (-1 for no node): 6
Enter left child of 6
Enter data for node (-1 for no node): -1
Enter right child of 6
Enter data for node (-1 for no node): 7
Enter left child of 7
Enter data for node (-1 for no node): -1
Enter right child of 7
Enter data for node (-1 for no node): -1
Enter right child of 8
Enter data for node (-1 for no node): 9
Enter left child of 9
Enter data for node (-1 for no node): -1
Enter right child of 9
Enter data for node (-1 for no node): -1

Output:
Post-Order Traversal: 4 3 7 6 9 8 5

Lab no. 1/S.NO.4& Write a program to


implement a menu-driven program for binary
tree traversal (in-order, pre-order, post-
order) and searching.

#include <stdio.h>
#include <stdlib.h>

// Define the structure for a node


struct Node {
int data;
struct Node* left;
struct Node* right;
};

// Function to create a new node


struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

// Function to insert a node in the binary tree


struct Node* insertNode(struct Node* root, int data) {
if (root == NULL) {
return createNode(data);
}
if (data < root->data) {
root->left = insertNode(root->left, data);
} else {
root->right = insertNode(root->right, data);
}
return root;
}

// Function for in-order traversal


void inOrder(struct Node* root) {
if (root != NULL) {
inOrder(root->left);
printf("%d ", root->data);
inOrder(root->right);
}
}

// Function for pre-order traversal


void preOrder(struct Node* root) {
if (root != NULL) {
printf("%d ", root->data);
preOrder(root->left);
preOrder(root->right);
}
}

// Function for post-order traversal


void postOrder(struct Node* root) {
if (root != NULL) {
postOrder(root->left);
postOrder(root->right);
printf("%d ", root->data);
}
}

// Function to search for a value in the binary tree


int searchNode(struct Node* root, int key) {
if (root == NULL) {
return 0; // Key not found
}
if (root->data == key) {
return 1; // Key found
}
if (key < root->data) {
return searchNode(root->left, key);
}
return searchNode(root->right, key);
}

// Main function
int main() {
struct Node* root = NULL;
int choice, value, searchValue;

printf("Binary Tree Menu:\n");


printf("1. Insert Node\n");
printf("2. In-order Traversal\n");
printf("3. Pre-order Traversal\n");
printf("4. Post-order Traversal\n");
printf("5. Search for a Node\n");
printf("6. Exit\n");

while (1) {
printf("\nEnter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter value to insert: ");
scanf("%d", &value);
root = insertNode(root, value);
break;

case 2:
printf("In-order Traversal: ");
inOrder(root);
printf("\n");
break;

case 3:
printf("Pre-order Traversal: ");
preOrder(root);
printf("\n");
break;

case 4:
printf("Post-order Traversal: ");
postOrder(root);
printf("\n");
break;

case 5:
printf("Enter value to search: ");
scanf("%d", &searchValue);
if (searchNode(root, searchValue)) {
printf("Value %d found in the tree.\n", searchValue);
} else {
printf("Value %d not found in the tree.\n", searchValue);
}
break;

case 6:
printf("Exiting...\n");
exit(0);

default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
}
Test Case 1:
Binary Tree Menu:
1. Insert Node
2. In-order Traversal
3. Pre-order Traversal
4. Post-order Traversal
5. Search for a Node
6. Exit

Enter your choice: 1


Enter value to insert: 50

Enter your choice: 1


Enter value to insert: 30

Enter your choice: 2


In-order Traversal: 30 50

Enter your choice: 5


Enter value to search: 30
Value 30 found in the tree.

Enter your choice: 6


Exiting...

Test Case 2:
Binary Tree Menu:
1. Insert Node
2. In-order Traversal
3. Pre-order Traversal
4. Post-order Traversal
5. Search for a Node
6. Exit

Enter your choice: 1


Enter value to insert: 10

Enter your choice: 1


Enter value to insert: 5

Enter your choice: 1


Enter value to insert: 15

Enter your choice: 2


In-order Traversal: 5 10 15

Enter your choice: 3


Pre-order Traversal: 10 5 15

Enter your choice: 4


Post-order Traversal: 5 15 10

Enter your choice: 5


Enter value to search: 15
Value 15 found in the tree.

Enter your choice: 6


Exiting...
Lab no. 1/S.NO.5& Count Number of Nodes in a
Binary Tree

#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Function to create a new node
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
// Function to construct the tree by taking user input
struct Node* constructTree() {
int data;
printf("Enter data for node (-1 for no node): ");
scanf("%d", &data);
// If the user enters -1, return NULL (no node)
if (data == -1)
return NULL;
struct Node* newNode = createNode(data);
printf("Enter left child of %d\n", data);
newNode->left = constructTree();
printf("Enter right child of %d\n", data);
newNode->right = constructTree();
return newNode;
}
// Function to count the total number of nodes
int countNodes(struct Node* root) {
if (root == NULL)
return 0;
return 1 + countNodes(root->left) + countNodes(root->right);
}

int main() {
struct Node* root = NULL;
// Build the tree with user input
printf("Construct the binary tree:\n");
root = constructTree();
// Count and display the total number of nodes
printf("Total number of nodes: %d\n", countNodes(root));
return 0;
}

Test Case 1:
Input:
Enter data for node (-1 for no node): 1
Enter left child of 1
Enter data for node (-1 for no node): 2
Enter left child of 2
Enter data for node (-1 for no node): 4
Enter left child of 4
Enter data for node (-1 for no node): -1
Enter right child of 4
Enter data for node (-1 for no node): -1
Enter right child of 2
Enter data for node (-1 for no node): 5
Enter left child of 5
Enter data for node (-1 for no node): -1
Enter right child of 5
Enter data for node (-1 for no node): -1
Enter right child of 1
Enter data for node (-1 for no node): 3
Enter left child of 3
Enter data for node (-1 for no node): -1
Enter right child of 3
Enter data for node (-1 for no node): -1

Total number of nodes: 5


Test Case 2:
Input:

Enter data for node (-1 for no node): 10


Enter left child of 10
Enter data for node (-1 for no node): 20
Enter left child of 20
Enter data for node (-1 for no node): 30
Enter left child of 30
Enter data for node (-1 for no node): -1
Enter right child of 30
Enter data for node (-1 for no node): -1
Enter right child of 20
Enter data for node (-1 for no node): -1
Enter right child of 10
Enter data for node (-1 for no node): 40
Enter left child of 40
Enter data for node (-1 for no node): -1
Enter right child of 40
Enter data for node (-1 for no node): -1

Total number of nodes: 4

Test Case 3:
Input:
Enter data for node (-1 for no node): 5
Enter left child of 5
Enter data for node (-1 for no node): 8
Enter left child of 8
Enter data for node (-1 for no node): 12
Enter left child of 12
Enter data for node (-1 for no node): -1
Enter right child of 12
Enter data for node (-1 for no node): -1
Enter right child of 8
Enter data for node (-1 for no node): 15
Enter left child of 15
Enter data for node (-1 for no node): -1
Enter right child of 15
Enter data for node (-1 for no node): -1
Enter right child of 5
Enter data for node (-1 for no node): 10
Enter left child of 10
Enter data for node (-1 for no node): -1
Enter right child of 10
Enter data for node (-1 for no node): -1
Total number of nodes: 6

Lab no. 1/S.NO.6& Find the Height of a Binary


Tree
#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* left;
struct Node* right;
};

struct Node* createNode(int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}

// Function to calculate height of the tree


int height(struct Node* root) {
if (root == NULL)
return 0;
int leftHeight = height(root->left);
int rightHeight = height(root->right);
return 1 + (leftHeight > rightHeight ? leftHeight : rightHeight);
}

// Function to insert nodes into the binary tree (creating a simple binary tree)
struct Node* insertNode(struct Node* root, int data) {
if (root == NULL) {
return createNode(data);
}
printf("Do you want to add %d to the left (L) or right (R) of %d? ", data, root->data);
char choice;
scanf(" %c", &choice); // Space before %c to capture any leftover newline character

if (choice == 'L' || choice == 'l') {


root->left = insertNode(root->left, data);
} else if (choice == 'R' || choice == 'r') {
root->right = insertNode(root->right, data);
} else {
printf("Invalid choice! Please enter L or R.\n");
}
return root;
}

int main() {
int n, data;

// Take number of nodes in the tree as input


printf("Enter the number of nodes: ");
scanf("%d", &n);

if (n <= 0) {
printf("Invalid number of nodes.\n");
return 0;
}

printf("Enter the root node value: ");


scanf("%d", &data);

struct Node* root = createNode(data);

// Insert other nodes


for (int i = 1; i < n; i++) {
printf("Enter data for node %d: ", i+1);
scanf("%d", &data);
root = insertNode(root, data);
}

// Print the height of the tree


printf("Height of the tree: %d\n", height(root));

return 0;
}

Test case 1 :
Enter the number of nodes: 3
Enter the root node value: 1
Enter data for node 2: 2
Do you want to add 2 to the left (L) or right (R) of 1? L
Enter data for node 3: 3
Do you want to add 3 to the left (L) or right (R) of 1? R
Height of the tree: 2

Test Case 2:
Enter the number of nodes: 5
Enter the root node value: 10
Enter data for node 2: 20
Do you want to add 20 to the left (L) or right (R) of 10? L
Enter data for node 3: 30
Do you want to add 30 to the left (L) or right (R) of 20? L
Enter data for node 4: 40
Do you want to add 40 to the left (L) or right (R) of 30? L
Enter data for node 5: 50
Do you want to add 50 to the left (L) or right (R) of 40? L
Height of the tree: 5

Test Case 3:
Enter the number of nodes: 0
Invalid number of nodes.

Lab no. 1/S.NO.7& Check if a Binary Tree is


Balanced

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h> // Include math.h for abs() function

struct Node {
int data;
struct Node* left;
struct Node* right;
};

struct Node* createNode(int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}

int height(struct Node* root) {


if (root == NULL)
return 0;
int leftHeight = height(root->left);
int rightHeight = height(root->right);
return 1 + (leftHeight > rightHeight ? leftHeight : rightHeight);
}

bool isBalanced(struct Node* root) {


if (root == NULL)
return true;
int leftHeight = height(root->left);
int rightHeight = height(root->right);
if (abs(leftHeight - rightHeight) > 1)
return false;
return isBalanced(root->left) && isBalanced(root->right);
}

struct Node* insertNode(struct Node* root, int data) {


if (root == NULL) {
return createNode(data);
}

char choice;
printf("Do you want to add %d to the left (L) or right (R) of %d? ", data, root->data);
scanf(" %c", &choice); // Space before %c to capture any leftover newline character

if (choice == 'L' || choice == 'l') {


root->left = insertNode(root->left, data);
} else if (choice == 'R' || choice == 'r') {
root->right = insertNode(root->right, data);
} else {
printf("Invalid choice! Please enter L or R.\n");
}
return root;
}

int main() {
int i,n, data;

// Take number of nodes in the tree as input


printf("Enter the number of nodes: ");
scanf("%d", &n);
if (n <= 0) {
printf("Invalid number of nodes.\n");
return 0;
}

printf("Enter the root node value: ");


scanf("%d", &data);
struct Node* root = createNode(data);
// Insert other nodes
for (i = 1; i < n; i++) {
printf("Enter data for node %d: ", i + 1);
scanf("%d", &data);
root = insertNode(root, data);
}
// Check if the tree is balanced
if (isBalanced(root)) {
printf("The tree is balanced.\n");
} else {
printf("The tree is not balanced.\n");
}
return 0;
}

Test Case 1:
Enter the number of nodes: 5
Enter the root node value: 1
Enter data for node 2: 2
Do you want to add 2 to the left (L) or right (R) of 1? L
Enter data for node 3: 3
Do you want to add 3 to the left (L) or right (R) of 2? R
Enter data for node 4: 4
Do you want to add 4 to the left (L) or right (R) of 3? L
Enter data for node 5: 5
Do you want to add 5 to the left (L) or right (R) of 4? R
The tree is balanced.

Test Case 2:
Enter the number of nodes: 4
Enter the root node value: 10
Enter data for node 2: 20
Do you want to add 20 to the left (L) or right (R) of 10? R
Enter data for node 3: 30
Do you want to add 30 to the left (L) or right (R) of 20? R
Enter data for node 4: 40
Do you want to add 40 to the left (L) or right (R) of 30? R
The tree is not balanced.

Test Case 3:
Enter the number of nodes: 3
Enter the root node value: 10
Enter data for node 2: 20
Do you want to add 20 to the left (L) or right (R) of 10? L
Enter data for node 3: 30
Do you want to add 30 to the left (L) or right (R) of 10? R
The tree is balanced.

Lab no. 1/S.NO.8& Search a Number in a


Binary Search Tree (BST)

#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* left;
struct Node* right;
};

struct Node* createNode(int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}

struct Node* insert(struct Node* root, int data) {


if (root == NULL)
return createNode(data);
if (data < root->data)
root->left = insert(root->left, data);
else if (data > root->data)
root->right = insert(root->right, data);
return root;
}

int search(struct Node* root, int key) {


if (root == NULL)
return 0;
if (root->data == key)
return 1;
if (key < root->data)
return search(root->left, key);
return search(root->right, key);
}

int main() {
struct Node* root = NULL;
int n, key;

printf("Enter number of elements to insert in BST: ");


scanf("%d", &n); // Input number of elements

printf("Enter elements:\n");
for (int i = 0; i < n; i++) {
int x;
scanf("%d", &x); // Input the elements
root = insert(root, x);
}

printf("Enter the number to search: ");


scanf("%d", &key); // Input the number to search

if (search(root, key))
printf("Number found in BST.\n");
else
printf("Number not found in BST.\n");

return 0;
}

Test Case 1:
Enter number of elements to insert in BST: 5
Enter elements:
20
10
30
5
15
Enter the number to search: 15
Number found in BST.

Test Case 2:
Enter number of elements to insert in BST: 4
Enter elements:
50
30
70
20
Enter the number to search: 60
Number not found in BST.

Test Case 3:
Enter number of elements to insert in BST: 6
Enter elements:
40
20
60
10
30
50
Enter the number to search: 30
Number found in BST.

Lab no. 1/S.NO.9& Insert a Node in a Binary


Search Tree (BST)
#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* left;
struct Node* right;
};

struct Node* createNode(int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}

struct Node* insert(struct Node* root, int data) {


if (root == NULL)
return createNode(data);
if (data < root->data)
root->left = insert(root->left, data);
else if (data > root->data)
root->right = insert(root->right, data);
return root;
}

void inorderTraversal(struct Node* root) {


if (root == NULL)
return;
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}

int main() {
struct Node* root = NULL;
int i, n;
printf("Enter number of elements to insert in BST: ");
scanf("%d", &n);
printf("Enter elements:");
for (i = 0; i < n; i++) {
int x;
scanf("%d", &x);
root = insert(root, x);
}
printf("In-Order Traversal after insertion: ");
inorderTraversal(root);
return 0;
}

Test case 1:
Enter number of elements to insert in BST: 5
Enter elements:
30
20
40
10
25
In-Order Traversal after insertion: 10 20 25 30 40

Test Case 2:
Enter number of elements to insert in BST: 4
Enter elements:
50
30
70
60
In-Order Traversal after insertion: 30 50 60 70

Test Case 3:
Enter number of elements to insert in BST: 6
Enter elements:
15
10
20
8
12
18
In-Order Traversal after insertion: 8 10 12 15 18 20

Lab no. 1/S.NO.10. Delete a Node from a Binary Search


Tree (BST)
#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* left;
struct Node* right;
};

struct Node* createNode(int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}

struct Node* insert(struct Node* root, int data) {


if (root == NULL)
return createNode(data);
if (data < root->data)
root->left = insert(root->left, data);
else if (data > root->data)
root->right = insert(root->right, data);
return root;
}
struct Node* findMin(struct Node* root) {
while (root && root->left != NULL)
root = root->left;
return root;
}

struct Node* deleteNode(struct Node* root, int key) {


if (root == NULL)
return root;
if (key < root->data)
root->left = deleteNode(root->left, key);
else if (key > root->data)
root->right = deleteNode(root->right, key);
else {
if (root->left == NULL) {
struct Node* temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL) {
struct Node* temp = root->left;
free(root);
return temp;
}
struct Node* temp = findMin(root->right);
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
return root;
}

void inorderTraversal(struct Node* root) {


if (root == NULL)
return;
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}

int main() {
struct Node* root = NULL;
int i,n, key;
printf("Enter number of elements to insert in BST: ");
scanf("%d", &n);
printf("Enter elements:");
for (i = 0; i < n; i++) {
int x;
scanf("%d", &x);
root = insert(root, x);
}
printf("Enter the number to delete: ");
scanf("%d", &key);
root = deleteNode(root, key);
printf("In-Order Traversal after deletion: ");
inorderTraversal(root);
return 0;
}

Test case1:
Enter number of elements to insert in BST: 7
Enter elements:
50 30 70 20 40 60 80
Enter the number to delete: 70
In-Order Traversal after deletion: 20 30 40 50 60 80

Test Case 2:
Enter number of elements to insert in BST: 5
Enter elements:
10 5 15 3 7
Enter the number to delete: 3
In-Order Traversal after deletion: 5 7 10 15

Test Case 3:
Enter number of elements to insert in BST: 6
Enter elements:
50 30 70 20 40 60
Enter the number to delete: 50
In-Order Traversal after deletion: 20 30 40 60 70

Lab no. 1/S.NO.11&. Implement a Max-Heap and Perform


Heap Sort on an Array of Integers
#include <stdio.h>

void swap(int* a, int* b) {


int temp = *a;
*a = *b;
*b = temp;
}
void heapify(int arr[], int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;

if (left < n && arr[left] > arr[largest])


largest = left;
if (right < n && arr[right] > arr[largest])
largest = right;
if (largest != i) {
swap(&arr[i], &arr[largest]);
heapify(arr, n, largest);
}
}

void heapSort(int arr[], int n) {


int i;
for (i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (i = n - 1; i >= 0; i--) {
swap(&arr[0], &arr[i]);
heapify(arr, i, 0);
}
}

void printArray(int arr[], int n) {


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

int main() {
int n,i;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter the elements:");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
heapSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}

Test Case 1:
Enter the number of elements: 6
Enter the elements: 12 11 13 5 6 7
Sorted array: 5 6 7 11 12 13

Test Case 2:
Enter the number of elements: 1
Enter the elements: 42
Sorted array: 42

Test Case 3:
Enter the number of elements: 5
Enter the elements: 9 9 9 9 9
Sorted array: 9 9 9 9 9

Lab no. 1/S.NO.12. Implement Insertion and Search


Operations in a Tree
#include <stdio.h>
#include <stdlib.h>

// Define the structure for a tree node


typedef struct Node {
int data;
struct Node *left, *right;
} Node;

// Function to create a new node


Node* createNode(int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

// Function to insert a node in the binary search tree


Node* insert(Node* root, int value) {
if (root == NULL) {
// If tree is empty, create a new node
return createNode(value);
}
if (value < root->data) {
// Insert in the left subtree
root->left = insert(root->left, value);
} else if (value > root->data) {
// Insert in the right subtree
root->right = insert(root->right, value);
}
return root;
}

// Function to search for a value in the binary search tree


int search(Node* root, int value) {
if (root == NULL) {
// Value not found
return 0;
}
if (root->data == value) {
// Value found
return 1;
}
if (value < root->data) {
// Search in the left subtree
return search(root->left, value);
} else {
// Search in the right subtree
return search(root->right, value);
}
}

// Function for in-order traversal


void inOrderTraversal(Node* root) {
if (root != NULL) {
inOrderTraversal(root->left);
printf("%d ", root->data);
inOrderTraversal(root->right);
}
}

int main() {
Node* root = NULL;
int choice, value;

while (1) {
printf("\nBinary Search Tree Operations:\n");
printf("1. Insert\n");
printf("2. Search\n");
printf("3. Display (In-order Traversal)\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter value to insert: ");
scanf("%d", &value);
root = insert(root, value);
printf("%d inserted successfully.\n", value);
break;

case 2:
printf("Enter value to search: ");
scanf("%d", &value);
if (search(root, value)) {
printf("%d found in the tree.\n", value);
} else {
printf("%d not found in the tree.\n", value);
}
break;

case 3:
printf("In-order Traversal of the tree: ");
inOrderTraversal(root);
printf("\n");
break;

case 4:
printf("Exiting...\n");
exit(0);

default:
printf("Invalid choice! Please try again.\n");
}
}

return 0;
}

Test Case1:
Binary Search Tree Operations:
1. Insert
2. Search
3. Display (In-order Traversal)
4. Exit
Enter your choice: 1
Enter value to insert: 40

Enter your choice: 1


Enter value to insert: 20

Enter your choice: 1


Enter value to insert: 60

Enter your choice: 3

Enter your choice: 2


Enter value to search: 20

Enter your choice: 2


Enter value to search: 50

Enter your choice: 4


40 inserted successfully.
20 inserted successfully.
60 inserted successfully.
In-order Traversal of the tree: 20 40 60
20 found in the tree.
50 not found in the tree.
Exiting...

Test Case 2:

Binary Search Tree Operations:


1. Insert
2. Search
3. Display (In-order Traversal)
4. Exit
Enter your choice: 1
Enter value to insert: 1
1 inserted successfully.

Binary Search Tree Operations:


1. Insert
2. Search
3. Display (In-order Traversal)
4. Exit
Enter your choice: 1
Enter value to insert: 3
3 inserted successfully.

Binary Search Tree Operations:


1. Insert
2. Search
3. Display (In-order Traversal)
4. Exit
Enter your choice: 1
Enter value to insert: 5
5 inserted successfully.

Binary Search Tree Operations:


1. Insert
2. Search
3. Display (In-order Traversal)
4. Exit
Enter your choice: 2
Enter value to search: 1
1 found in the tree.

Binary Search Tree Operations:


1. Insert
2. Search
3. Display (In-order Traversal)
4. Exit
Enter your choice: 3
In-order Traversal of the tree: 1 3 5

Binary Search Tree Operations:


1. Insert
2. Search
3. Display (In-order Traversal)
4. Exit
Enter your choice: 4
Exiting...
Lab no. 1/S.NO.13. Write a program to calculate the
balance factor of each node of the AVL tree.

#include <stdio.h>
#include <stdlib.h>

// Define the structure for the node


struct Node {
int data;
struct Node* left;
struct Node* right;
};

// Create a new node


struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

// Insert a node into the binary tree


void insertNode(struct Node* root, int data) {
struct Node* current = root;
while (1) {
if (data < current->data) {
if (current->left == NULL) {
current->left = createNode(data);
break;
} else {
current = current->left;
}
} else {
if (current->right == NULL) {
current->right = createNode(data);
break;
} else {
current = current->right;
}
}
}
}
// Calculate the height of a subtree
int calculateHeight(struct Node* node) {
if (node == NULL)
return 0;
int leftHeight = calculateHeight(node->left);
int rightHeight = calculateHeight(node->right);
return 1 + (leftHeight > rightHeight ? leftHeight : rightHeight);
}

// Print the balance factor of each node


void printBalanceFactors(struct Node* root) {
if (root == NULL)
return;

int leftHeight = calculateHeight(root->left);


int rightHeight = calculateHeight(root->right);
int balanceFactor = leftHeight - rightHeight;

printf("Node %d: Balance Factor = %d\n", root->data, balanceFactor);

// Recur for left and right children


printBalanceFactors(root->left);
printBalanceFactors(root->right);
}

// Main function
int main() {
struct Node* root = NULL;
int choice, data;

printf("Binary Tree Creation:\n");

while (1) {
printf("\nMenu:\n");
printf("1. Insert Node\n");
printf("2. Print Balance Factors\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter the value to insert: ");
scanf("%d", &data);
if (root == NULL) {
root = createNode(data); // Initialize root
} else {
insertNode(root, data);
}
break;

case 2:
if (root == NULL) {
printf("Tree is empty.\n");
} else {
printf("Balance Factors of the Nodes:\n");
printBalanceFactors(root);
}
break;

case 3:
printf("Exiting...\n");
return 0;

default:
printf("Invalid choice. Try again.\n");
}
}
return 0;
}

Test Case1:
Binary Tree Creation:

Menu:
1. Insert Node
2. Print Balance Factors
3. Exit
Enter your choice: 1
Enter the value to insert: 50

Menu:
1. Insert Node
2. Print Balance Factors
3. Exit
Enter your choice: 1
Enter the value to insert: 30

Menu:
1. Insert Node
2. Print Balance Factors
3. Exit
Enter your choice: 1
Enter the value to insert: 70

Menu:
1. Insert Node
2. Print Balance Factors
3. Exit
Enter your choice: 2
Balance Factors of the Nodes:
Node 50: Balance Factor = 0
Node 30: Balance Factor = 0
Node 70: Balance Factor = 0

Test Case 2:
1. Insert Node -> 50
2. Insert Node -> 30
3. Insert Node -> 20
4. Insert Node -> 40
5. Insert Node -> 10
6. Print Balance Factors
Balance Factors of the Nodes:
Node 50: Balance Factor = 2
Node 30: Balance Factor = 1
Node 20: Balance Factor = 1
Node 40: Balance Factor = 0
Node 10: Balance Factor = 0
Lab no. 1/S.NO.14&Implement Priority Queue Using Max
Heap

#include <stdio.h>
#include <stdlib.h>

#define MAX 1000

int heap[MAX];
int heapSize = 0;

void insert(int element) {


heap[heapSize++] = element;
int i = heapSize - 1;
while (i != 0 && heap[(i - 1) / 2] < heap[i]) {
int temp = heap[i];
heap[i] = heap[(i - 1) / 2];
heap[(i - 1) / 2] = temp;
i = (i - 1) / 2;
}
}

int extractMax() {
if (heapSize <= 0)
return -1;
if (heapSize == 1) {
heapSize--;
return heap[0];
}
int root = heap[0];
heap[0] = heap[--heapSize];
int i = 0;
while (1) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < heapSize && heap[left] > heap[largest])
largest = left;
if (right < heapSize && heap[right] > heap[largest])
largest = right;
if (largest == i)
break;
int temp = heap[i];
heap[i] = heap[largest];
heap[largest] = temp;
i = largest;
}
return root;
}

int main() {
int n, element;
printf("Enter the number of elements to insert: ");
scanf("%d", &n);

printf("Enter %d elements:\n", n);


for (int i = 0; i < n; i++) {
scanf("%d", &element);
insert(element);
}

printf("Extracted max: %d\n", extractMax());


printf("Extracted max: %d\n", extractMax());
return 0;
}

Test Case 1:
Enter the number of elements to insert: 5
Enter 5 elements:
10
20
15
30
25
Extracted max: 30
Extracted max: 25

Test case 2:
Enter the number of elements to insert: 3
Enter 3 elements:
5
3
8
Extracted max: 8
Extracted max: 5

Test Case 3:
Enter the number of elements to insert: 7
Enter 7 elements:
1
2
3
4
5
6
7
Extracted max: 7
Extracted max: 6

Lab no. 1/S.NO.15. Create a Graph Using an Adjacency


Matrix

#include <stdio.h>

#define MAX 10

void createGraph(int graph[MAX][MAX], int vertices) {


int i, j;
printf("\nPlease enter the adjacency matrix for the graph:\n");
for (i = 0; i < vertices; i++) {
for (j = 0; j < vertices; j++) {
printf("Enter the edge weight between vertex %d and vertex %d: ", i + 1, j + 1);
scanf("%d", &graph[i][j]);
}
}
}

void displayGraph(int graph[MAX][MAX], int vertices) {


int i, j;
printf("\nAdjacency Matrix Representation of the Graph:\n");
printf(" ");
for (i = 0; i < vertices; i++) {
printf("V%d ", i + 1); // Labeling columns with vertex numbers
}
printf("\n");

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


printf("V%d ", i + 1); // Labeling rows with vertex numbers
for (j = 0; j < vertices; j++) {
printf("%d ", graph[i][j]);
}
printf("\n");
}
}

int main() {
int graph[MAX][MAX];
int vertices;

// Asking the user for the number of vertices in the graph


printf("Please enter the number of vertices for your graph (max %d): ", MAX);
scanf("%d", &vertices);

// Checking if the input number of vertices is within the allowed limit


if (vertices > MAX || vertices <= 0) {
printf("Invalid number of vertices. Please enter a number between 1 and %d.\n", MAX);
return 1;
}

// Creating the graph by getting the adjacency matrix


createGraph(graph, vertices);

// Displaying the adjacency matrix of the graph


displayGraph(graph, vertices);

return 0;
}

Test Case 1 :
Please enter the number of vertices for your graph (max 10): 1
Please enter the adjacency matrix for the graph:
Enter the edge weight between vertex 1 and vertex 1: 0
Adjacency Matrix Representation of the Graph:
V1
V1 0

Test Case 2:
Please enter the number of vertices for your graph (max 10): 3
Please enter the adjacency matrix for the graph:
Enter the edge weight between vertex 1 and vertex 1: 0
Enter the edge weight between vertex 1 and vertex 2: 1
Enter the edge weight between vertex 1 and vertex 3: 0
Enter the edge weight between vertex 2 and vertex 1: 1
Enter the edge weight between vertex 2 and vertex 2: 0
Enter the edge weight between vertex 2 and vertex 3: 1
Enter the edge weight between vertex 3 and vertex 1: 0
Enter the edge weight between vertex 3 and vertex 2: 1
Enter the edge weight between vertex 3 and vertex 3: 0

Adjacency Matrix Representation of the Graph:


V1 V2 V3
V1 0 1 0
V2 1 0 1
V3 0 1 0

Test case 3:
Please enter the number of vertices for your graph (max 10): 11
Invalid number of vertices. Please enter a number between 1 and 10.

Lab no. 1/S.NO.16. Create a Graph Using an Adjacency


List
#include <stdio.h>

#define MAX_VERTICES 10

// Structure for the graph using an adjacency matrix


struct Graph {
int adjMatrix[MAX_VERTICES][MAX_VERTICES];
int numVertices;
};

void initializeGraph(struct Graph *graph, int vertices) {


int i, j;
graph->numVertices = vertices;
// Initialize all entries in the adjacency matrix to 0
for (i = 0; i < vertices; i++) {
for (j = 0; j < vertices; j++) {
graph->adjMatrix[i][j] = 0;
}
}
}

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


// As it is an undirected graph, we mark both adjacencies
graph->adjMatrix[src][dest] = 1;
graph->adjMatrix[dest][src] = 1;
}
void printGraph(struct Graph *graph) {
int i, j;
printf("\nAdjacency Matrix:\n ");
for (i = 0; i < graph->numVertices; i++) {
printf("V%d ", i);
}
printf("\n");

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


printf("V%d ", i);
for (j = 0; j < graph->numVertices; j++) {
printf("%d ", graph->adjMatrix[i][j]);
}
printf("\n");
}
}

int main() {
struct Graph graph;
int i, vertices, edges, src, dest;

// Input for the number of vertices


printf("Enter the number of vertices (Max %d): ", MAX_VERTICES);
scanf("%d", &vertices);

if (vertices <= 0 || vertices > MAX_VERTICES) {


printf("Invalid number of vertices.\n");
return 1;
}

// Initialize the graph


initializeGraph(&graph, vertices);

// Input for the number of edges


printf("Enter the number of edges (Max %d): ", vertices * (vertices - 1) / 2);
scanf("%d", &edges);

if (edges < 0 || edges > (vertices * (vertices - 1) / 2)) {


printf("Invalid number of edges.\n");
return 1;
}

// Input for each edge


for (i = 0; i < edges; i++) {
printf("Enter edge %d (source destination): ", i + 1);
scanf("%d %d", &src, &dest);

if (src < 0 || src >= vertices || dest < 0 || dest >= vertices) {
printf("Invalid vertices!\n");
i--; // Redo the invalid edge input
} else {
addEdge(&graph, src, dest);
}
}

// Print the adjacency matrix


printGraph(&graph);

return 0;
}

Test Case 1:
Enter the number of vertices (Max 10): 3
Enter the number of edges (Max 3): 2
Enter edge 1 (source destination): 0 1
Enter edge 2 (source destination): 1 2
Adjacency Matrix:
V0 V1 V2
V0 0 1 0
V1 1 0 1
V2 0 1 0

Test Case 2:
Enter the number of vertices (Max 10): 12
Invalid number of vertices.

Test Case 3:
Enter the number of vertices (Max 10): 4
Enter the number of edges (Max 6): -2
Invalid number of edges.

Lab no. 1/S.NO.17. Perform Depth-First Search (DFS) on a


Graph
#include <stdio.h>
#define MAX 100 // Maximum number of vertices in the graph
int graph[MAX][MAX]; // Adjacency matrix to represent the graph
int visited[MAX]; // Array to keep track of visited nodes

void dfs(int start, int vertices) {


int i;
printf("%d ", start); // Print the current vertex
visited[start] = 1; // Mark the current vertex as visited
for (i = 0; i < vertices; i++) {
if (graph[start][i] == 1 && visited[i] == 0) { // If there is an edge and the node is not visited
dfs(i, vertices); // Recursively visit the connected vertex
}
}
}

int main() {
int vertices, edges;
int v1, v2,i,j;
printf("Enter the number of vertices: ");
scanf("%d", &vertices);
printf("Enter the number of edges: ");
scanf("%d", &edges);
// Initialize the graph and visited arrays
for (i = 0; i < vertices; i++) {
for (j = 0; j < vertices; j++) {
graph[i][j] = 0;
}
visited[i] = 0;
}
printf("Enter the edges (format: v1 v2):\n");
for (i = 0; i < edges; i++) {
scanf("%d %d", &v1, &v2);
graph[v1][v2] = 1; // Mark the edge in the adjacency matrix
graph[v2][v1] = 1; // For undirected graph
}
int start;
printf("Enter the starting vertex for DFS: ");
scanf("%d", &start);
printf("DFS Traversal starting from vertex %d:\n", start);
dfs(start, vertices);
return 0;
}

Test Case 1:
Enter the number of vertices: 4
Enter the number of edges: 4
Enter the edges (format: v1 v2):
01
02
12
23
Enter the starting vertex for DFS: 0
DFS Traversal starting from vertex 0:
0123

Test Case 2
Enter the number of vertices: 6
Enter the number of edges: 4
Enter the edges (format: v1 v2):
01
02
34
45
Enter the starting vertex for DFS: 0
DFS Traversal starting from vertex 0:
012

Test Case 3
Enter the number of vertices: 1
Enter the number of edges: 0
Enter the starting vertex for DFS: 0
DFS Traversal starting from vertex 0:
0

Lab no. 1/S.NO.18. Perform Breadth-First Search (BFS) on


a Graph
#include <stdio.h>
#define MAX 100 // Maximum number of vertices in the graph

int graph[MAX][MAX]; // Adjacency matrix to represent the graph


int visited[MAX]; // Array to keep track of visited nodes
int queue[MAX]; // Queue for BFS
int front = -1, rear = -1; // Front and rear pointers for the queue

// Enqueue operation
void enqueue(int vertex) {
if (rear == MAX - 1) {
printf("Queue overflow\n");
return;
}
if (front == -1) front = 0;
queue[++rear] = vertex;
}

// Dequeue operation
int dequeue() {
if (front == -1 || front > rear) {
printf("Queue underflow\n");
return -1;
}
return queue[front++];
}

// BFS function
void bfs(int start, int vertices) {
int i;
printf("%d ", start); // Print the starting vertex
visited[start] = 1; // Mark it as visited
enqueue(start); // Enqueue the starting vertex

while (front <= rear) {


int current = dequeue(); // Dequeue a vertex
for (i = 0; i < vertices; i++) {
if (graph[current][i] == 1 && visited[i] == 0) { // Check for unvisited neighbors
printf("%d ", i); // Print the vertex
visited[i] = 1; // Mark as visited
enqueue(i); // Enqueue the vertex
}
}
}
}

int main() {
int vertices, edges;
int v1, v2, i, j;
printf("Enter the number of vertices: ");
scanf("%d", &vertices);
printf("Enter the number of edges: ");
scanf("%d", &edges);
// Initialize the graph and visited arrays
for (i = 0; i < vertices; i++) {
for (j = 0; j < vertices; j++) {
graph[i][j] = 0;
}
visited[i] = 0;
}
printf("Enter the edges (format: v1 v2):\n");
for (i = 0; i < edges; i++) {
scanf("%d %d", &v1 &v2);
graph[v1][v2] = 1; // Mark the edge in the adjacency matrix
graph[v2][v1] = 1; // For undirected graph
}
int start;
printf("Enter the starting vertex for BFS: ");
scanf("%d", &start);
printf("BFS Traversal starting from vertex %d:\n", start);
bfs(start, vertices);
return 0;
}

Test Case 1:

Enter the number of vertices: 4


Enter the number of edges: 4
Enter the edges (format: v1 v2):
01
02
12
23
Enter the starting vertex for BFS: 0
BFS Traversal starting from vertex 0:
0123

Test Case 2:
Enter the number of vertices: 6
Enter the number of edges: 4
Enter the edges (format: v1 v2):
01
02
34
45
Enter the starting vertex for BFS: 0
BFS Traversal starting from vertex 0:
012
Test Case 3:
Enter the number of vertices: 1
Enter the number of edges: 0
Enter the starting vertex for BFS: 0
BFS Traversal starting from vertex 0:
0

Lab no. 1/S.NO.19. Check if There is a Path Between Two


Nodes in a Graph Using DFS
Description: This program demonstrates 17. check if there is a path between two nodes in a
graph using dfs. Below is the C implementation.

#include <stdio.h>
#include <stdbool.h>
#define MAX 100

int graph[MAX][MAX];
int visited[MAX];

bool DFS(int current, int destination, int vertices) {


int i;
if (current == destination)
return true;
visited[current] = 1;
for (i = 0; i < vertices; i++) {
if (graph[current][i] && !visited[i]) {
if (DFS(i, destination, vertices))
return true;
}
}
return false;
}

int main() {
int vertices, edges, i, j, src, dest, addEdge;

printf("Enter number of vertices (Max %d): ", MAX);


scanf("%d", &vertices);

if (vertices <= 0 || vertices > MAX) {


printf("Invalid number of vertices. Exiting...\n");
return 1;
}
// Initialize the graph with no edges
for (i = 0; i < vertices; i++) {
for (j = 0; j < vertices; j++) {
graph[i][j] = 0;
}
}

printf("You can add edges between nodes from 0 to %d.\n", vertices - 1);

// Ask user to add edges


for (src = 0; src < vertices; src++) {
for (dest = src + 1; dest < vertices; dest++) {
printf("Do you want to add an edge between node %d and node %d? (1 for Yes, 0 for
No): ", src, dest);
scanf("%d", &addEdge);

if (addEdge == 1) {
graph[src][dest] = 1;
graph[dest][src] = 1; // Undirected graph
printf("Edge added between node %d and node %d.\n", src, dest);
}
}
}

printf("Enter source and destination nodes to check for a path (0 to %d): ", vertices - 1);
scanf("%d %d", &src, &dest);

// Check if the source and destination nodes are valid


if (src < 0 || src >= vertices || dest < 0 || dest >= vertices) {
printf("Invalid source or destination node.\n");
return 1;
}

// Initialize visited array


for (i = 0; i < vertices; i++) {
visited[i] = 0;
}

// Perform DFS to check for path


if (DFS(src, dest, vertices)) {
printf("Path exists between node %d and node %d.\n", src, dest);
} else {
printf("No path exists between node %d and node %d.\n", src, dest);
}

return 0;
}

Test Case 1:
Enter number of vertices (Max 100): 3
You can add edges between nodes from 0 to 2.
Do you want to add an edge between node 0 and node 1? (1 for Yes, 0 for No): 1
Edge added between node 0 and node 1.
Do you want to add an edge between node 0 and node 2? (1 for Yes, 0 for No): 0
Do you want to add an edge between node 1 and node 2? (1 for Yes, 0 for No): 0
Enter source and destination nodes to check for a path (0 to 2): 0 2
No path exists between node 0 and node 2.

Test Case 2:
Enter number of vertices (Max 100): 4
You can add edges between nodes from 0 to 3.
Do you want to add an edge between node 0 and node 1? (1 for Yes, 0 for No): 1
Edge added between node 0 and node 1.
Do you want to add an edge between node 0 and node 2? (1 for Yes, 0 for No): 1
Edge added between node 0 and node 2.
Do you want to add an edge between node 1 and node 2? (1 for Yes, 0 for No): 0
Do you want to add an edge between node 1 and node 3? (1 for Yes, 0 for No): 1
Edge added between node 1 and node 3.
Do you want to add an edge between node 2 and node 3? (1 for Yes, 0 for No): 0
Enter source and destination nodes to check for a path (0 to 3): 0 3
Path exists between node 0 and node 3.

Test Case 3:
Enter number of vertices (Max 100): 5
You can add edges between nodes from 0 to 4.
Do you want to add an edge between node 0 and node 1? (1 for Yes, 0 for No): 1
Edge added between node 0 and node 1.
Do you want to add an edge between node 0 and node 2? (1 for Yes, 0 for No): 1
Edge added between node 0 and node 2.
Do you want to add an edge between node 1 and node 2? (1 for Yes, 0 for No): 0
Do you want to add an edge between node 1 and node 3? (1 for Yes, 0 for No): 1
Edge added between node 1 and node 3.
Do you want to add an edge between node 1 and node 4? (1 for Yes, 0 for No): 0
Do you want to add an edge between node 2 and node 3? (1 for Yes, 0 for No): 1
Edge added between node 2 and node 3.
Do you want to add an edge between node 2 and node 4? (1 for Yes, 0 for No): 1
Edge added between node 2 and node 4.
Do you want to add an edge between node 3 and node 4? (1 for Yes, 0 for No): 0
Enter source and destination nodes to check for a path (0 to 4): 0 4
Path exists between node 0 and node 4.

Lab no. 1/S.NO.20. Find All Vertices Reachable from a


Given Vertex in a Graph Using BFS

#include <stdio.h>
#include <stdlib.h>

#define MAX 100

int graph[MAX][MAX];
int visited[MAX];

void BFS(int start, int vertices) {


int queue[MAX], i, front = 0, rear = 0;
printf("Reachable vertices from %d: ", start);
visited[start] = 1;
queue[rear++] = start;

while (front < rear) {


int vertex = queue[front++];
for (i = 0; i < vertices; i++) {
if (graph[vertex][i] && !visited[i]) {
printf("%d ", i);
visited[i] = 1;
queue[rear++] = i;
}
}
}
printf("\n");
}

int main() {
int vertices, i, j, edges = 0, src, dest, start;
int addEdge;

// User input for vertices


printf("Enter number of vertices (Max %d): ", MAX);
scanf("%d", &vertices);
if (vertices <= 0 || vertices > MAX) {
printf("Invalid number of vertices. Exiting...\n");
return 1;
}

// Initialize the graph with no edges


for (i = 0; i < vertices; i++) {
for (j = 0; j < vertices; j++) {
graph[i][j] = 0;
}
}

printf("You can add edges between nodes from 0 to %d.\n", vertices - 1);

// Ask user to add edges between pairs of nodes


for (i = 0; i < vertices; i++) {
for (j = i + 1; j < vertices; j++) { // Only need to ask once for each pair (i, j)
printf("Do you want to add an edge between node %d and node %d? (1 for yes, 0 for
no): ", i, j);
scanf("%d", &addEdge);

if (addEdge == 1) {
// Add the edge to the graph
graph[i][j] = 1;
graph[j][i] = 1; // Undirected graph
printf("Edge added between node %d and node %d.\n", i, j);
edges++;
} else {
printf("No edge added between node %d and node %d.\n", i, j);
}
}
}

printf("You have added %d edges in total.\n", edges);

// User input for starting vertex


printf("Enter the starting vertex (0 to %d): ", vertices - 1);
scanf("%d", &start);

// Validate the starting vertex


if (start < 0 || start >= vertices) {
printf("Invalid starting vertex. Exiting...\n");
return 1;
}

// Initialize visited array


for (i = 0; i < vertices; i++) {
visited[i] = 0;
}

// Perform BFS to find reachable vertices


BFS(start, vertices);

return 0;
}

Test Case 1:
Enter number of vertices (Max 100): 3
You can add edges between nodes from 0 to 2.
Do you want to add an edge between node 0 and node 1? (1 for yes, 0 for no): 1
Edge added between node 0 and node 1.
Do you want to add an edge between node 0 and node 2? (1 for yes, 0 for no): 1
Edge added between node 0 and node 2.
Do you want to add an edge between node 1 and node 2? (1 for yes, 0 for no): 1
Edge added between node 1 and node 2.
You have added 3 edges in total.
Enter the starting vertex (0 to 2): 0
Reachable vertices from 0: 0 1 2

Test Case 2:
Enter number of vertices (Max 100): 4
You can add edges between nodes from 0 to 3.
Do you want to add an edge between node 0 and node 1? (1 for yes, 0 for no): 1
Edge added between node 0 and node 1.
Do you want to add an edge between node 0 and node 2? (1 for yes, 0 for no): 0
No edge added between node 0 and node 2.
Do you want to add an edge between node 0 and node 3? (1 for yes, 0 for no): 0
No edge added between node 0 and node 3.
Do you want to add an edge between node 1 and node 2? (1 for yes, 0 for no): 0
No edge added between node 1 and node 2.
Do you want to add an edge between node 1 and node 3? (1 for yes, 0 for no): 0
No edge added between node 1 and node 3.
Do you want to add an edge between node 2 and node 3? (1 for yes, 0 for no): 1
Edge added between node 2 and node 3.
You have added 2 edges in total.
Enter the starting vertex (0 to 3): 0
Reachable vertices from 0: 0 1

Test Case 3:
Enter number of vertices (Max 100): 5
You can add edges between nodes from 0 to 4.
Do you want to add an edge between node 0 and node 1? (1 for yes, 0 for no): 1
Edge added between node 0 and node 1.
Do you want to add an edge between node 0 and node 2? (1 for yes, 0 for no): 0
No edge added between node 0 and node 2.
Do you want to add an edge between node 0 and node 3? (1 for yes, 0 for no): 0
No edge added between node 0 and node 3.
Do you want to add an edge between node 0 and node 4? (1 for yes, 0 for no): 0
No edge added between node 0 and node 4.
Do you want to add an edge between node 1 and node 2? (1 for yes, 0 for no): 1
Edge added between node 1 and node 2.
Do you want to add an edge between node 1 and node 3? (1 for yes, 0 for no): 0
No edge added between node 1 and node 3.
Do you want to add an edge between node 1 and node 4? (1 for yes, 0 for no): 0
No edge added between node 1 and node 4.
Do you want to add an edge between node 2 and node 3? (1 for yes, 0 for no): 1
Edge added between node 2 and node 3.
Do you want to add an edge between node 2 and node 4? (1 for yes, 0 for no): 0
No edge added between node 2 and node 4.
Do you want to add an edge between node 3 and node 4? (1 for yes, 0 for no): 0
No edge added between node 3 and node 4.
You have added 3 edges in total.
Enter the starting vertex (0 to 4): 0
Reachable vertices from 0: 0 1 2

Lab no. 1/S.NO.21. Detect a Cycle in an Undirected Graph


Using DFS
Description: This program demonstrates 19. detect a cycle in an undirected graph using dfs.
Below is the C implementation.

#include <stdio.h>
#include <stdbool.h>

#define MAX 100

int graph[MAX][MAX];
int visited[MAX];

bool detectCycleDFS(int vertex, int parent, int vertices) {


visited[vertex] = 1;
for (int i = 0; i < vertices; i++) {
if (graph[vertex][i]) {
if (!visited[i]) {
if (detectCycleDFS(i, vertex, vertices))
return true;
} else if (i != parent) {
return true;
}
}
}
return false;
}

int main() {
int vertices, edges, src, dest;
printf("Enter number of vertices and edges: ");
scanf("%d %d", &vertices, &edges);
printf("Enter edges (src dest):");
for (int i = 0; i < edges; i++) {
scanf("%d %d", &src, &dest);
graph[src][dest] = 1;
graph[dest][src] = 1; // Undirected graph
}
if (detectCycleDFS(0, -1, vertices))
printf("Cycle detected in the graph.");
else
printf("No cycle detected in the graph.");
return 0;
}

Lab no. 1/S.NO.22. Detect a Cycle in a Directed Graph


Using DFS
Description: This program demonstrates 20. detect a cycle in a directed graph using dfs. Below
is the C implementation.

#include <stdio.h>
#include <stdbool.h>

#define MAX 100

// Function to perform DFS and check for a cycle


bool dfs(int graph[MAX][MAX], int visited[], int recursionStack[], int node, int vertices) {
int neighbor;
visited[node] = 1;
recursionStack[node] = 1;

for (neighbor = 0; neighbor < vertices; neighbor++) {


if (graph[node][neighbor]) { // Check if there's an edge
if (!visited[neighbor]) {
if (dfs(graph, visited, recursionStack, neighbor, vertices)) {
return true; // Cycle detected
}
} else if (recursionStack[neighbor]) {
return true; // Cycle detected
}
}
}

recursionStack[node] = 0; // Remove from recursion stack


return false;
}

// Function to check for a cycle in the graph


bool isCyclic(int graph[MAX][MAX], int vertices) {
int i ;
int visited[MAX] = {0};
int recursionStack[MAX] = {0};

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


if (!visited[i]) {
if (dfs(graph, visited, recursionStack, i, vertices)) {
return true; // Cycle detected
}
}
}
return false; // No cycle detected
}

int main() {
int i;
int vertices, edges;
printf("Enter the number of vertices: ");
scanf("%d", &vertices);

int graph[MAX][MAX] = {0};


printf("Enter the number of edges: ");
scanf("%d", &edges);

printf("Enter the edges (start end):\n");


for (i = 0; i < edges; i++) {
int start, end;
scanf("%d %d", &start, &end);
graph[start][end] = 1;
}

if (isCyclic(graph, vertices)) {
printf("The graph contains a cycle.\n");
} else {
printf("The graph does not contain a cycle.\n");
}

return 0;
}

Test Case1:

Enter the number of vertices: 4


Enter the number of edges: 4
Enter the edges (start end):
01
12
23
31
The graph contains a cycle.

Test Case 2:
Enter the number of vertices: 4
Enter the number of edges: 3
Enter the edges (start end):
01
12
23
The graph does not contain a cycle.
Lab no. 1/S.NO.23.. Find the Degree of Each Vertex in an
Undirected Graph
Description: This program demonstrates 21. find the degree of each vertex in an undirected
graph. Below is the C implementation.

#include <stdio.h>

#define MAX 100

int main() {
int graph[MAX][MAX] = {0};
int vertices, edges;

// Input the number of vertices


printf("Enter the number of vertices: ");
scanf("%d", &vertices);

// Input the number of edges


printf("Enter the number of edges: ");
scanf("%d", &edges);

// Input the edges


printf("Enter the edges (start end):\n");
for (int i = 0; i < edges; i++) {
int start, end;
scanf("%d %d", &start, &end);

// Since the graph is undirected, mark both directions


graph[start][end] = 1;
graph[end][start] = 1;
}

// Calculate and print the degree of each vertex


printf("Degree of each vertex:\n");
for (int i = 0; i < vertices; i++) {
int degree = 0;
for (int j = 0; j < vertices; j++) {
if (graph[i][j] == 1) {
degree++;
}
}
printf("Vertex %d: Degree %d\n", i, degree);
}

return 0;
}

Test Case1:
Enter the number of vertices: 4
Enter the number of edges: 4
Enter the edges (start end):
01
02
12
23
Degree of each vertex:
Vertex 0: Degree 2
Vertex 1: Degree 2
Vertex 2: Degree 3
Vertex 3: Degree 1

Test Case 2:
Enter the number of vertices: 3
Enter the number of edges: 2
Enter the edges (start end):
01
12
Degree of each vertex:
Vertex 0: Degree 1
Vertex 1: Degree 2
Vertex 2: Degree 1
Lab no. 1/S.NO.24. Count the Number of Connected
Components in an Undirected Graph
#include <stdio.h>
#include <stdbool.h>
#define MAX 100
// Function to perform DFS
void dfs(int graph[MAX][MAX], bool visited[], int vertex, int vertices) {
visited[vertex] = true;
for (int i = 0; i < vertices; i++) {
if (graph[vertex][i] == 1 && !visited[i]) {
dfs(graph, visited, i, vertices);
}
}
}
// Function to count connected components
int countConnectedComponents(int graph[MAX][MAX], int vertices) {
bool visited[MAX] = {false};
int count = 0;
for (int i = 0; i < vertices; i++) {
if (!visited[i]) {
dfs(graph, visited, i, vertices);
count++;
}
}
return count;
}
int main() {
int graph[MAX][MAX] = {0};
int vertices, edges;
// Input the number of vertices
printf("Enter the number of vertices: ");
scanf("%d", &vertices);
// Input the number of edges
printf("Enter the number of edges: ");
scanf("%d", &edges);
// Input the edges
printf("Enter the edges (start end):\n");
for (int i = 0; i < edges; i++) {
int start, end;
scanf("%d %d", &start, &end);
// Since the graph is undirected, mark both directions
graph[start][end] = 1;
graph[end][start] = 1; }
// Count and display the number of connected components
int result = countConnectedComponents(graph, vertices);
printf("The number of connected components in the graph is: %d\n", result);

return 0;
}

Test Case 1:
Enter the number of vertices: 6
Enter the number of edges: 3
Enter the edges (start end):
01
23
45
The number of connected components in the graph is: 3

Test Case2:
Enter the number of vertices: 4
Enter the number of edges: 2
Enter the edges (start end):
01
23
The number of connected components in the graph is: 2

Lab no. 1/S.NO.25. Implement Dijkstra's


Algorithm
#include <stdio.h>
#include <limits.h>
#include <stdbool.h>

#define MAX 100

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


int findMinDistance(int dist[], bool visited[], int vertices) {
int min = INT_MAX, minIndex;
int v;
for (v = 0; v < vertices; v++) {
if (!visited[v] && dist[v] <= min) {
min = dist[v];
minIndex = v;
}
}
return minIndex;
}

// Function to implement Dijkstra's algorithm


void dijkstra(int graph[MAX][MAX], int vertices, int startVertex) {
int dist[MAX]; // Array to store the shortest distances
bool visited[MAX]; // Array to track visited vertices
int u,v,i,count;
// Initialize distances to infinity and visited array to false
for (i = 0; i < vertices; i++) {
dist[i] = INT_MAX;
visited[i] = false;
}

dist[startVertex] = 0; // Distance from source to itself is always 0

// Find shortest path for all vertices


for (count = 0; count < vertices - 1; count++) {
u = findMinDistance(dist, visited, vertices); // Pick the minimum distance vertex
visited[u] = true;

// Update distances of adjacent vertices


for (v = 0; v < vertices; v++) {
if (!visited[v] && graph[u][v] && dist[u] != INT_MAX
&& dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}

// Print the shortest distances


printf("Vertex\tDistance from Source\n");
for (i = 0; i < vertices; i++) {
printf("%d\t%d\n", i, dist[i]);
}
}

int main() {
int graph[MAX][MAX], vertices, edges;
int i,j;
// Input the number of vertices
printf("Enter the number of vertices: ");
scanf("%d", &vertices);
// Input the number of edges
printf("Enter the number of edges: ");
scanf("%d", &edges);

// Initialize the graph with 0s


for (i = 0; i < vertices; i++) {
for (j = 0; j < vertices; j++) {
graph[i][j] = 0;
}
}

// Input the edges and weights


printf("Enter the edges with weights (start end weight):\n");
for (i = 0; i < edges; i++) {
int start, end, weight;
scanf("%d %d %d", &start, &end, &weight);
graph[start][end] = weight;
graph[end][start] = weight; // For undirected graph
}

int startVertex;
printf("Enter the starting vertex: ");
scanf("%d", &startVertex);

// Perform Dijkstra's Algorithm


dijkstra(graph, vertices, startVertex);

return 0;
}

Test Case 1:
Enter the number of vertices: 5
Enter the number of edges: 6
Enter the edges with weights (start end weight):
012
024
121
137
243
341
Enter the starting vertex: 0
Vertex Distance from Source
0 0
1 2
2 3
3 9
4 6

Test Case 2
Enter the number of vertices: 4
Enter the number of edges: 4
Enter the edges with weights (start end weight):
015
0 2 10
122
133
Enter the starting vertex: 0
Vertex Distance from Source
0 0
1 5
2 7
3 8

Lab no. 1/S.NO.26. Implement Prim's


Algorithm
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>

#define MAX 100

// Function to find the vertex with the minimum weight


int minweight(int weight[], bool visited[], int V)
{
int min = INT_MAX, min_index;

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


if (visited[v] == false && weight[v] < min) {
min = weight[v];
min_index = v;
}
}
return min_index;
}

// Function to print the constructed MST and its total cost


void printMST(int parent[], int graph[MAX][MAX], int V)
{
int totalCost = 0;

printf("MST for the graph:\n");


printf("Edge \tWeight\n");
for (int i = 1; i < V; i++) {
printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);
totalCost += graph[i][parent[i]];
}
printf("Total cost of MST: %d\n", totalCost);
}

// Function to construct and print MST for a graph


void primMST(int graph[MAX][MAX], int V)
{
int parent[MAX]; // Array to store constructed MST
int weight[MAX]; // Array to store the weights
bool visited[MAX]; // To represent set of vertices included in MST

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


weight[i] = INT_MAX;
visited[i] = false;
}

weight[0] = 0;
parent[0] = -1;

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


int u = minweight(weight, visited, V);

visited[u] = true;

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


if (graph[u][v] && !visited[v] && graph[u][v] < weight[v]) {
parent[v] = u;
weight[v] = graph[u][v];
}
}
}

printMST(parent, graph, V);


}
int main()
{
int V;
int graph[MAX][MAX];

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


scanf("%d", &V);

printf("Enter the adjacency matrix of the graph (use 0 for no direct edge):\n");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
printf("Edge weight between vertex %d and %d: ", i, j);
scanf("%d", &graph[i][j]);
}
}

primMST(graph, V);

return 0;
}

Enter the number of vertices: 5

Enter the adjacency matrix of the graph (use 0 for no direct edge):
Edge weight between vertex 0 and 0: 0
Edge weight between vertex 0 and 1: 2
Edge weight between vertex 0 and 2: 0
Edge weight between vertex 0 and 3: 6
Edge weight between vertex 0 and 4: 0
Edge weight between vertex 1 and 0: 2
Edge weight between vertex 1 and 1: 0
Edge weight between vertex 1 and 2: 3
Edge weight between vertex 1 and 3: 8
Edge weight between vertex 1 and 4: 5
Edge weight between vertex 2 and 0: 0
Edge weight between vertex 2 and 1: 3
Edge weight between vertex 2 and 2: 0
Edge weight between vertex 2 and 3: 0
Edge weight between vertex 2 and 4: 7
Edge weight between vertex 3 and 0: 6
Edge weight between vertex 3 and 1: 8
Edge weight between vertex 3 and 2: 0
Edge weight between vertex 3 and 3: 0
Edge weight between vertex 3 and 4: 9
Edge weight between vertex 4 and 0: 0
Edge weight between vertex 4 and 1: 5
Edge weight between vertex 4 and 2: 7
Edge weight between vertex 4 and 3: 9
Edge weight between vertex 4 and 4: 0

MST for the graph:


Edge Weight
0-1 2
1-2 3
0-3 6
1-4 5
Total cost of MST: 16

Test Case 2 :

Enter the number of vertices: 4

Enter the adjacency matrix of the graph (use 0 for no direct edge):
Edge weight between vertex 0 and 0: 0
Edge weight between vertex 0 and 1: 10
Edge weight between vertex 0 and 2: 6
Edge weight between vertex 0 and 3: 5
Edge weight between vertex 1 and 0: 10
Edge weight between vertex 1 and 1: 0
Edge weight between vertex 1 and 2: 15
Edge weight between vertex 1 and 3: 0
Edge weight between vertex 2 and 0: 6
Edge weight between vertex 2 and 1: 15
Edge weight between vertex 2 and 2: 0
Edge weight between vertex 2 and 3: 4
Edge weight between vertex 3 and 0: 5
Edge weight between vertex 3 and 1: 0
Edge weight between vertex 3 and 2: 4
Edge weight between vertex 3 and 3: 0

MST for the graph:


Edge Weight
3-2 4
3-0 5
0 - 1 10
Total cost of MST: 19
Lab no. 1/S.NO.27. Implement Kruskal's Algorithm
#include <stdio.h>
#include <stdlib.h>

#define MAX 100

// Structure to represent an edge


typedef struct {
int source, destination, weight;
} Edge;

// Structure to represent a graph


typedef struct {
int V, E; // Number of vertices and edges
Edge edges[MAX];
} Graph;

// Structure to represent a subset for union-find


typedef struct {
int parent, rank;
} Subset;

// Function to compare two edges by their weights


int compareEdges(const void* a, const void* b) {
Edge* edgeA = (Edge*)a;
Edge* edgeB = (Edge*)b;
return edgeA->weight - edgeB->weight;
}

// Function to find the subset of an element (using path compression)


int find(Subset subsets[], int i) {
if (subsets[i].parent != i)
subsets[i].parent = find(subsets, subsets[i].parent);
return subsets[i].parent;
}

// Function to unite two subsets (union by rank)


void unionSubsets(Subset subsets[], int x, int y) {
int rootX = find(subsets, x);
int rootY = find(subsets, y);

if (subsets[rootX].rank < subsets[rootY].rank) {


subsets[rootX].parent = rootY;
} else if (subsets[rootX].rank > subsets[rootY].rank) {
subsets[rootY].parent = rootX;
} else {
subsets[rootY].parent = rootX;
subsets[rootX].rank++;
}
}

// Function to find MST using Kruskal's Algorithm


void kruskalMST(Graph* graph) {
int V = graph->V;
Edge result[MAX]; // To store the resulting MST
int e = 0; // Index for result[]
int i = 0; // Index for sorted edges

// Step 1: Sort all edges by weight


qsort(graph->edges, graph->E, sizeof(graph->edges[0]), compareEdges);

// Allocate memory for creating subsets


Subset* subsets = (Subset*)malloc(V * sizeof(Subset));

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


subsets[v].parent = v;
subsets[v].rank = 0;
}

// Iterate through sorted edges and build MST


while (e < V - 1 && i < graph->E) {
Edge nextEdge = graph->edges[i++];

int x = find(subsets, nextEdge.source);


int y = find(subsets, nextEdge.destination);

// If including this edge doesn't form a cycle


if (x != y) {
result[e++] = nextEdge;
unionSubsets(subsets, x, y);
}
}

// Print the MST and its total cost


int totalCost = 0;
printf("MST for the graph:\n");
printf("Edge \tWeight\n");
for (int j = 0; j < e; ++j) {
printf("%d - %d \t%d\n", result[j].source, result[j].destination, result[j].weight);
totalCost += result[j].weight;
}
printf("Total cost of MST: %d\n", totalCost);

// Free allocated memory


free(subsets);
}

int main() {
Graph graph;
printf("Enter the number of vertices: ");
scanf("%d", &graph.V);

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


scanf("%d", &graph.E);

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


for (int i = 0; i < graph.E; i++) {
printf("Edge %d: ", i + 1);
scanf("%d %d %d", &graph.edges[i].source, &graph.edges[i].destination,
&graph.edges[i].weight);
}
kruskalMST(&graph);
return 0;
}
Test Case 1:
Enter the number of vertices: 4
Enter the number of edges: 5
Enter the edges (source, destination, weight):
Edge 1: 0 1 10
Edge 2: 0 2 6
Edge 3: 0 3 5
Edge 4: 1 3 15
Edge 5: 2 3 4
MST for the graph:
Edge Weight
2-3 4
0-3 5
0 - 1 10
Total cost of MST: 19
Test Case 2:
Enter the number of vertices: 4
Enter the edges (source, destination, weight):
MST for the graph:
Edge Weight
Total cost of MST: 0

Lab no. 1/S.NO.28. Implement Floyd-Warshall's All Pair


Shortest Path Algorithm
#include <stdio.h>

// Define the number of vertices as a maximum value


#define MAX 100

// Define Infinite as a large value for unreachable paths


#define INF 99999

// A function to print the solution matrix


void printSolution(int dist[][MAX], int V);

// Solves the all-pairs shortest path problem using Floyd Warshall algorithm
void floydWarshall(int dist[][MAX], int V)
{
int i, j, k;

// Add all vertices to the set of intermediate vertices


for (k = 0; k < V; k++) {
// Pick all vertices as source one by one
for (i = 0; i < V; i++) {
// Pick all vertices as destination for the above picked source
for (j = 0; j < V; j++) {
// If vertex k is on the shortest path from i to j, update the value of dist[i][j]
if (dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}

// Print the shortest distance matrix


printSolution(dist, V);
}

// A utility function to print the solution


void printSolution(int dist[][MAX], int V)
{
printf("The following matrix shows the shortest distances between every pair of vertices:\n");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][j] == INF)
printf("%7s", "INF");
else
printf("%7d", dist[i][j]);
}
printf("\n");
}
}

// Driver code
int main()
{
int V, E;
int graph[MAX][MAX];

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


scanf("%d", &V);

// Initialize the graph with INF (no direct connection)


for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (i == j)
graph[i][j] = 0; // Distance to self is 0
else
graph[i][j] = INF; // Initialize all other distances to INF
}
}

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


scanf("%d", &E);

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


for (int i = 0; i < E; i++) {
int u, v, w;
printf("Edge %d: ", i + 1);
scanf("%d %d %d", &u, &v, &w);
graph[u][v] = w; // Directed graph
}

// Perform Floyd Warshall algorithm


floydWarshall(graph, V);

return 0;
}

Test Case 1 :
Enter the number of vertices: 4
Enter the number of edges: 4
Enter the edges (source, destination, weight):
Edge 1: 0 1 5
Edge 2: 0 2 10
Edge 3: 1 3 15
Edge 4: 2 3 20

The following matrix shows the shortest distances between every pair of vertices:
0 5 10 20
INF 0 INF 15
INF INF 0 20
INF INF INF 0

Test Case 2
Enter the number of vertices: 5
Enter the number of edges: 6
Enter the edges (source, destination, weight):
Edge 1: 0 1 2
Edge 2: 1 2 3
Edge 3: 0 3 8
Edge 4: 3 4 1
Edge 5: 4 1 7
Edge 6: 2 4 5

The following matrix shows the shortest distances between every pair of vertices:
0 2 5 8 9
INF 0 3 INF 8
INF INF 0 INF 5
INF 9 12 0 1
INF 7 10 INF 0
Lab no. 1/S.NO.29. Implement Bellman-Ford Algorithm
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

// Define maximum number of vertices


#define MAX_VERTICES 1000
// Define infinity for initialization
#define INF INT_MAX

// Define Bellman-Ford function


void bellmanFord(int graph[][3], int vertices, int edges, int source) {
// Declare distance array
int distance[MAX_VERTICES];

// Initialize distances from source to all vertices as infinity


for (int i = 0; i < vertices; ++i)
distance[i] = INF;
// Distance from source to itself is 0
distance[source] = 0;

// Relax edges V-1 times


for (int i = 0; i < vertices - 1; ++i) {
for (int j = 0; j < edges; ++j) {
if (distance[graph[j][0]] != INF &&
distance[graph[j][1]] > distance[graph[j][0]] + graph[j][2]) {
distance[graph[j][1]] = distance[graph[j][0]] + graph[j][2];
}
}
}

// Check for negative cycles


for (int i = 0; i < edges; ++i) {
if (distance[graph[i][0]] != INF &&
distance[graph[i][1]] > distance[graph[i][0]] + graph[i][2]) {
printf("Negative cycle detected\n");
return;
}
}

// Print shortest distances from source to all vertices


printf("Vertex Distance from Source\n");
for (int i = 0; i < vertices; ++i) {
if (distance[i] == INF)
printf("%d \t\t INF\n", i);
else
printf("%d \t\t %d\n", i, distance[i]);
}
}

// Define main function


int main() {
int vertices, edges, source;

// Input number of vertices and edges


printf("Enter the number of vertices: ");
scanf("%d", &vertices);
printf("Enter the number of edges: ");
scanf("%d", &edges);

// Input the edges of the graph


int graph[MAX_VERTICES][3];
printf("Enter the edges (source destination weight):\n");
for (int i = 0; i < edges; ++i) {
printf("Edge %d: ", i + 1);
scanf("%d %d %d", &graph[i][0], &graph[i][1], &graph[i][2]);
}

// Input the source vertex


printf("Enter the source vertex: ");
scanf("%d", &source);
// Call Bellman-Ford function
bellmanFord(graph, vertices, edges, source);
return 0;
}

Test case 1:

Enter the number of vertices: 4


Enter the number of edges: 5
Enter the edges (source destination weight):
Edge 1: 0 1 4
Edge 2: 0 2 5
Edge 3: 1 2 -3
Edge 4: 1 3 6
Edge 5: 2 3 2
Enter the source vertex: 0
Vertex Distance from Source
0 0
1 4
2 1
3 3

Test Case 2:

Enter the number of vertices: 3


Enter the number of edges: 3
Enter the edges (source destination weight):
Edge 1: 0 1 1
Edge 2: 1 2 -1
Edge 3: 2 0 -1
Enter the source vertex: 0

Negative cycle detected


Lab no. 1/S.NO.30. Implement Longest Common
Subsequence (LCS)
#include <stdio.h>
#include <string.h>

// Function to return the maximum of two integers


int max(int a, int b) {
return (a > b) ? a : b;
}

// Function to find the length of the Longest Common Subsequence (LCS) using recursion
int lcsRecursive(char* X, char* Y, int m, int n) {
// Base case: If either string is empty, LCS length is 0
if (m == 0 || n == 0)
return 0;

// If the characters match, include them in LCS and recur for the remaining strings
if (X[m - 1] == Y[n - 1])
return 1 + lcsRecursive(X, Y, m - 1, n - 1);

// If the characters do not match, recursively find LCS by excluding one character at a time
else
return max(lcsRecursive(X, Y, m, n - 1), lcsRecursive(X, Y, m - 1, n));
}

int main() {
// Define variables for input strings
char X[100], Y[100];

// Input first string


printf("Enter the first string: ");
scanf("%s", X);

// Input second string


printf("Enter the second string: ");
scanf("%s", Y);

// Length of first string


int m = strlen(X);
// Length of second string
int n = strlen(Y);

// Calculate and print the length of Longest Common Subsequence (LCS)


printf("Length of LCS is %d\n", lcsRecursive(X, Y, m, n));

return 0;
}

Test Case 1:
Enter the first string: ABCD
Enter the second string: ACBD
Length of LCS is 3

Test Case 2:
Enter the first string: XYZ
Enter the second string: YZXY
Length of LCS is 2

Lab no. 1/S.NO.31. Implement Sum of Subset Problem


Using Backtracking
#include <stdio.h>
#include <stdbool.h>

// Flag to check if at least one subset exists


bool flag = false;

// Function to print all subsets with sum equal to targetSum


void PrintSubsetSum(int i, int n, int set[], int targetSum, int subset[], int subsetSize) {
// If targetSum is 0, print the subset
int j;
if (targetSum == 0) {
flag = true;
printf("[ ");
for (j = 0; j < subsetSize; j++) {
printf("%d ", subset[j]);
}
printf("]\n");
return;
}

// If end of the set is reached, return


if (i == n) {
return;
}
// Exclude the current element and move to the next
PrintSubsetSum(i + 1, n, set, targetSum, subset, subsetSize);

// Include the current element if it is less than or equal to targetSum


if (set[i] <= targetSum) {
subset[subsetSize] = set[i];
PrintSubsetSum(i + 1, n, set, targetSum - set[i], subset, subsetSize + 1);
}
}

// Driver code
int main() {
int n, sum;

// Input the size of the set


printf("Enter the number of elements in the set: ");
scanf("%d", &n);

int set[n];
int subset[n],i; // Array to hold the subset

// Input the elements of the set


printf("Enter the elements of the set: ");
for (i = 0; i < n; i++) {
scanf("%d", &set[i]);
}

// Input the target sum


printf("Enter the target sum: ");
scanf("%d", &sum);

// Call the function to print subsets


printf("Subsets with sum %d:\n", sum);
PrintSubsetSum(0, n, set, sum, subset, 0);

if (!flag) {
printf("There is no such subset\n");
}

return 0;
}

Test Case 1:
Enter the number of elements in the set: 3
Enter the elements of the set: 1 2 1
Enter the target sum: 3
Subsets with sum 3:
[12]
[21]
[111]

Test Case 2:
Enter the number of elements in the set: 6
Enter the elements of the set: 3 34 4 12 5 2
Enter the target sum: 30
Subsets with sum 30:
There is no such subset

You might also like