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

Ds Lab Manual

The document is a lab manual for Compiler Design at Jawaharlal Nehru Technological University, Kakinada, detailing the construction and operations of AVL and B-Trees. It includes C code for inserting, deleting, and traversing AVL trees, as well as constructing a B-Tree of order 5 with operations for searching, inserting, and deleting. The manual provides a practical approach to understanding tree data structures through coding examples.

Uploaded by

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

Ds Lab Manual

The document is a lab manual for Compiler Design at Jawaharlal Nehru Technological University, Kakinada, detailing the construction and operations of AVL and B-Trees. It includes C code for inserting, deleting, and traversing AVL trees, as well as constructing a B-Tree of order 5 with operations for searching, inserting, and deleting. The manual provides a practical approach to understanding tree data structures through coding examples.

Uploaded by

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

lOMoARcPSD|15581981

DS lab Manual

compiler design (Jawaharlal Nehru Technological University, Kakinada)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Hanumantharao Murukutla ([email protected])
lOMoARcPSD|15581981

1)Construct an AVL tree for a given set of elements which are stored in a file. And
implement insert and delete operation on the constructed tree. Write contents of tree
into a new file using in-order.
#include <stdio.h>
#include <stdlib.h>
// An AVL tree node
struct Node {
int key;
struct Node* left;
struct Node* right;
int height;
};
// A utility function to get the height of the tree
int height(struct Node* N) {
if (N == NULL)
return 0;
return N->height;
}
// A utility function to get maximum of two integers
int max(int a, int b) {
return (a > b) ? a : b;
}
// A utility function to allocate a new node with the given key and NULL left and right pointers.
struct Node* newNode(int key) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1; // new node is initially added at leaf
return (node);
}
// A utility function to right rotate subtree rooted with y
struct Node* rightRotate(struct Node* y) {
struct Node* x = y->left;
struct Node* T2 = x->right;
// Perform rotation
x->right = y;
y->left = T2;

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

// Update heights
y->height = max(height(y->left), height(y->right)) + 1;
x->height = max(height(x->left), height(x->right)) + 1;
// Return new root
return x;
}
// A utility function to left rotate subtree rooted with x
struct Node* leftRotate(struct Node* x) {
struct Node* y = x->right;
struct Node* T2 = y->left;
// Perform rotation
y->left = x;
x->right = T2;
// Update heights
x->height = max(height(x->left), height(x->right)) + 1;
y->height = max(height(y->left), height(y->right)) + 1;
// Return new root
return y;
}

// Get Balance factor of node N


int getBalance(struct Node* N) {
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}
// Recursive function to insert a key in the subtree rooted with node and returns the new root of the
subtree.
struct Node* insert(struct Node* node, int key) {
// 1. Perform the normal BST insertion
if (node == NULL)
return (newNode(key));

if (key < node->key)


node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

else // Equal keys are not allowed in BST


return node;
// 2. Update height of this ancestor node
node->height = 1 + max(height(node->left), height(node->right));
// 3. Get the balance factor of this ancestor node to check whether this node became unbalanced
int balance = getBalance(node);
// If this node becomes unbalanced, then there are 4 cases
// Left Left Case
if (balance > 1 && key < node->left->key)
return rightRotate(node);
// Right Right Case
if (balance < -1 && key > node->right->key)
return leftRotate(node);
// Left Right Case
if (balance > 1 && key > node->left->key) {
node->left = leftRotate(node->left);
return rightRotate(node);
}
// Right Left Case
if (balance < -1 && key < node->right->key) {
node->right = rightRotate(node->right);
return leftRotate(node);
}
// return the (unchanged) node pointer
return node;
}

// A utility function to find the node with the minimum key value found in that tree.
struct Node* minValueNode(struct Node* node) {
struct Node* current = node;

// loop down to find the leftmost leaf


while (current->left != NULL)
current = current->left;
return current;
}

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

// Recursive function to delete a node with given key from subtree with given root. It returns root of
the modified subtree.
struct Node* deleteNode(struct Node* root, int key) {
// STEP 1: PERFORM STANDARD BST DELETE
if (root == NULL)
return root;

// If the key to be deleted is smaller than the root's key, then it lies in left subtree
if (key < root->key)
root->left = deleteNode(root->left, key);

// If the key to be deleted is greater than the root's key, then it lies in right subtree
else if (key > root->key)
root->right = deleteNode(root->right, key);

// if key is same as root's key, then This is the node to be deleted


else {
// node with only one child or no child
if ((root->left == NULL) || (root->right == NULL)) {
struct Node* temp = root->left ? root->left : root->right;

// No child case
if (temp == NULL) {
temp = root;
root = NULL;
} else // One child case
*root = *temp; // Copy the contents of the non-empty child
free(temp);
} else {
// node with two children: Get the inorder successor (smallest in the right subtree)
struct Node* temp = minValueNode(root->right);

// Copy the inorder successor's data to this node


root->key = temp->key;

// Delete the inorder successor


root->right = deleteNode(root->right, temp->key);
}

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

// If the tree had only one node then return


if (root == NULL)
return root;

// STEP 2: UPDATE HEIGHT OF THE CURRENT NODE


root->height = max(height(root->left), height(root->right)) + 1;

// STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to check whether this node became
unbalanced)
int balance = getBalance(root);

// If this node becomes unbalanced, then there are 4 cases

// Left Left Case


if (balance > 1 && getBalance(root->left) >= 0)
return rightRotate(root);

// Left Right Case


if (balance > 1 && getBalance(root->left) < 0) {
root->left = leftRotate(root->left);
return rightRotate(root);
}

// Right Right Case


if (balance < -1 && getBalance(root->right) <= 0)
return leftRotate(root);

// Right Left Case


if (balance < -1 && getBalance(root->right) > 0) {
root->right = rightRotate(root->right);
return leftRotate(root);
}

return root;
}

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

// A utility function to print inorder traversal of the tree


void inorder(struct Node* root, FILE* file) {
if (root != NULL) {
inorder(root->left, file);
fprintf(file, "%d ", root->key);
inorder(root->right, file);
}
}

// Function to read data from a file and construct an AVL tree


struct Node* constructAVLTree(char* filename) {
FILE* file = fopen(filename, "r");
if (!file) {
printf("Unable to open file\n");
return NULL;
}

struct Node* root = NULL;


int key;

while (fscanf(file, "%d", &key) != EOF) {


root = insert(root, key);
}

fclose(file);
return root;
}

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

// Construct the AVL tree from input file


root = constructAVLTree("input.txt");

// Perform some operations


root = insert(root, 20);
root = insert(root, 25);

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

root = deleteNode(root, 10);

// Write the contents of the tree to a new file using in-order traversal
FILE* outputFile = fopen("output.txt", "w");
if (!outputFile) {
printf("Unable to open file\n");
return 1;
}
inorder(root, outputFile);
fclose(outputFile);
return 0;
}

2. Construct B-Tree an order of 5 with a set of 100 random elements stored in array. Implement
searching, insertion and deletion operations.
#include <stdio.h>
#include <stdlib.h>
#define ORDER 5 // Maximum number of children a node can have
typedef struct BTreeNode {
int keys[ORDER - 1];
struct BTreeNode* children[ORDER];
int n; // Current number of keys
int leaf; // 1 if leaf node, otherwise 0
} BTreeNode;

typedef struct BTree {


BTreeNode* root;
} BTree;
BTreeNode* createNode(int leaf) {
BTreeNode* node = (BTreeNode*)malloc(sizeof(BTreeNode));
node->leaf = leaf;
node->n = 0;
for (int i = 0; i < ORDER; i++) {
node->children[i] = NULL;
}
return node;
}

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

BTree* createTree() {
BTree* tree = (BTree*)malloc(sizeof(BTree));
tree->root = createNode(1);
return tree;
}
BTreeNode* search(BTreeNode* node, int key) {
int i = 0;
while (i < node->n && key > node->keys[i]) {
i++;
}
if (i < node->n && key == node->keys[i]) {
return node;
}
if (node->leaf) {
return NULL;
}
return search(node->children[i], key);
}
void splitChild(BTreeNode* parent, int index, BTreeNode* child) {
BTreeNode* newChild = createNode(child->leaf);
newChild->n = ORDER / 2;

for (int j = 0; j < ORDER / 2; j++) {


newChild->keys[j] = child->keys[j + ORDER / 2];
}
if (!child->leaf) {
for (int j = 0; j <= ORDER / 2; j++) {
newChild->children[j] = child->children[j + ORDER / 2];
}
}
child->n = ORDER / 2 - 1;

for (int j = parent->n; j >= index + 1; j--) {


parent->children[j + 1] = parent->children[j];
}
parent->children[index + 1] = newChild;

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

for (int j = parent->n - 1; j >= index; j--) {


parent->keys[j + 1] = parent->keys[j];
}
parent->keys[index] = child->keys[ORDER / 2 - 1];
parent->n += 1;
}

void insertNonFull(BTreeNode* node, int key) {


int i = node->n - 1;
if (node->leaf) {
while (i >= 0 && key < node->keys[i]) {
node->keys[i + 1] = node->keys[i];
i--;
}
node->keys[i + 1] = key;
node->n += 1;
} else {
while (i >= 0 && key < node->keys[i]) {
i--;
}
i++;
if (node->children[i]->n == ORDER - 1) {
splitChild(node, i, node->children[i]);
if (key > node->keys[i]) {
i++;
}
}
insertNonFull(node->children[i], key);
}
}

void insert(BTree* tree, int key) {


BTreeNode* root = tree->root;
if (root->n == ORDER - 1) {
BTreeNode* newRoot = createNode(0);
newRoot->children[0] = root;
splitChild(newRoot, 0, root);

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

int i = 0;
if (newRoot->keys[0] < key) {
i++;
}
insertNonFull(newRoot->children[i], key);
tree->root = newRoot;
} else {
insertNonFull(root, key);
}
}
void merge(BTreeNode* node, int index) {
BTreeNode* child = node->children[index];
BTreeNode* sibling = node->children[index + 1];

child->keys[ORDER / 2 - 1] = node->keys[index];

for (int i = 0; i < sibling->n; i++) {


child->keys[i + ORDER / 2] = sibling->keys[i];
}
if (!child->leaf) {
for (int i = 0; i <= sibling->n; i++) {
child->children[i + ORDER / 2] = sibling->children[i];
}
}

for (int i = index + 1; i < node->n; i++) {


node->keys[i - 1] = node->keys[i];
}
for (int i = index + 2; i <= node->n; i++) {
node->children[i - 1] = node->children[i];
}

child->n += sibling->n + 1;
node->n--;

free(sibling);
}

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

void fill(BTreeNode* node, int index) {


if (index != 0 && node->children[index - 1]->n >= ORDER / 2) {
BTreeNode* child = node->children[index];
BTreeNode* sibling = node->children[index - 1];

for (int i = child->n - 1; i >= 0; i--) {


child->keys[i + 1] = child->keys[i];
}
if (!child->leaf) {
for (int i = child->n; i >= 0; i--) {
child->children[i + 1] = child->children[i];
}
}

child->keys[0] = node->keys[index - 1];


if (!node->leaf) {
child->children[0] = sibling->children[sibling->n];
}
node->keys[index - 1] = sibling->keys[sibling->n - 1];

child->n += 1;
sibling->n -= 1;
} else if (index != node->n && node->children[index + 1]->n >= ORDER / 2) {
BTreeNode* child = node->children[index];
BTreeNode* sibling = node->children[index + 1];

child->keys[child->n] = node->keys[index];
if (!(child->leaf)) {
child->children[child->n + 1] = sibling->children[0];
}
node->keys[index] = sibling->keys[0];

for (int i = 1; i < sibling->n; i++) {


sibling->keys[i - 1] = sibling->keys[i];
}
if (!sibling->leaf) {

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

for (int i = 1; i <= sibling->n; i++) {


sibling->children[i - 1] = sibling->children[i];
}
}
child->n += 1;
sibling->n -= 1;
} else {
if (index != node->n) {
merge(node, index);
} else {
merge(node, index - 1);
}
}
}

void removeFromLeaf(BTreeNode* node, int index) {


for (int i = index + 1; i < node->n; i++) {
node->keys[i - 1] = node->keys[i];
}
node->n--;
}

void removeFromNonLeaf(BTreeNode* node, int index) {


int key = node->keys[index];
if (node->children[index]->n >= ORDER / 2) {
BTreeNode* cur = node->children[index];
while (!cur->leaf) {
cur = cur->children[cur->n];
}
int pred = cur->keys[cur->n - 1];
node->keys[index] = pred;
deleteNode(node->children[index], pred);
} else if (node->children[index + 1]->n >= ORDER / 2) {
BTreeNode* cur = node->children[index + 1];
while (!cur->leaf) {
cur = cur->children[0];
}

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

int succ = cur->keys[0];


node->keys[index] = succ;
deleteNode(node->children[index + 1], succ);
} else {
merge(node, index);
deleteNode(node->children[index], key);
}
}

void deleteNode(BTreeNode* node, int key) {


int index = 0;
while (index < node->n && node->keys[index] < key) {
index++;
}
if (index < node->n && node->keys[index] == key) {
if (node->leaf) {
removeFromLeaf(node, index);
} else {
removeFromNonLeaf(node, index);
}
} else {
if (node->leaf) {
printf("Key %d not found in the tree\n", key);
return;
}
int flag = ((index == node->n) ? 1 : 0);
if (node->children[index]->n < ORDER / 2) {
fill(node, index);
}
if (flag && index > node->n) {
deleteNode(node->children[index - 1], key);
} else {
deleteNode(node->children[index], key);
}
}
}

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

void delete(BTree* tree, int key) {


if (!tree->root) {
printf("The tree is empty\n");
return;
}
deleteNode(tree->root, key);
if (tree->root->n == 0) {
BTreeNode* tmp = tree->root;
if (tree->root->leaf) {
tree->root = NULL;
} else {
tree->root = tree->root->children[0];
}
free(tmp);
}
}
int main() {
BTree* tree = createTree();

// Insert random elements


for (int i = 0; i < 100; i++) {
insert(tree, rand() % 1000);
}

// Perform search operations


int key = 50;
BTreeNode* result = search(tree->root, key);
if (result != NULL) {
printf("Key %d found in the tree\n", key);
} else {
printf("Key %d not found in the tree\n", key);
}

// Perform deletion
delete(tree, key);
result = search(tree->root, key);
if (result != NULL) {

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

printf("Key %d found in the tree\n", key);


} else {
printf("Key %d not found in the tree\n", key);
}

return 0;
}

3.Construct Min and Max Heap using arrays, delete any element and display the content
of the Heap.
#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 100

typedef struct MinHeap {


int size;
int arr[MAX_SIZE];
} MinHeap;

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


int temp = *a;
*a = *b;
*b = temp;
}
void minHeapify(MinHeap *heap, int index) {
int smallest = index;
int left = 2 * index + 1;
int right = 2 * index + 2;

if (left < heap->size && heap->arr[left] < heap->arr[smallest]) {


smallest = left;
}
if (right < heap->size && heap->arr[right] < heap->arr[smallest]) {
smallest = right;
}
if (smallest != index) {
swap(&heap->arr[smallest], &heap->arr[index]);

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

minHeapify(heap, smallest);
}
}

void insertMinHeap(MinHeap *heap, int key) {


if (heap->size == MAX_SIZE) {
printf("Heap overflow\n");
return;
}
heap->size++;
int i = heap->size - 1;
heap->arr[i] = key;
while (i != 0 && heap->arr[(i - 1) / 2] > heap->arr[i]) {
swap(&heap->arr[i], &heap->arr[(i - 1) / 2]);
i = (i - 1) / 2;
}
}

int deleteMin(MinHeap *heap, int key) {


int i;
for (i = 0; i < heap->size; i++) {
if (heap->arr[i] == key) {
break;
}
}
if (i == heap->size) {
return -1; // Key not found
}
swap(&heap->arr[i], &heap->arr[heap->size - 1]);
heap->size--;
minHeapify(heap, i);
return key;
}
void displayMinHeap(MinHeap *heap) {
for (int i = 0; i < heap->size; i++) {
printf("%d ", heap->arr[i]);
}

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

printf("\n");
}
typedef struct MaxHeap {
int size;
int arr[MAX_SIZE];
} MaxHeap;
void maxHeapify(MaxHeap *heap, int index) {
int largest = index;
int left = 2 * index + 1;
int right = 2 * index + 2;

if (left < heap->size && heap->arr[left] > heap->arr[largest]) {


largest = left;
}
if (right < heap->size && heap->arr[right] > heap->arr[largest]) {
largest = right;
}
if (largest != index) {
swap(&heap->arr[largest], &heap->arr[index]);
maxHeapify(heap, largest);
}
}

void insertMaxHeap(MaxHeap *heap, int key) {


if (heap->size == MAX_SIZE) {
printf("Heap overflow\n");
return;
}
heap->size++;
int i = heap->size - 1;
heap->arr[i] = key;
while (i != 0 && heap->arr[(i - 1) / 2] < heap->arr[i]) {
swap(&heap->arr[i], &heap->arr[(i - 1) / 2]);
i = (i - 1) / 2;
}
}

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

int deleteMax(MaxHeap *heap, int key) {


int i;
for (i = 0; i < heap->size; i++) {
if (heap->arr[i] == key) {
break;
}
}
if (i == heap->size) {
return -1; // Key not found
}
swap(&heap->arr[i], &heap->arr[heap->size - 1]);
heap->size--;
maxHeapify(heap, i);
return key;
}
void displayMaxHeap(MaxHeap *heap) {
for (int i = 0; i < heap->size; i++) {
printf("%d ", heap->arr[i]);
}
printf("\n");
}
int main() {
MinHeap minHeap;
minHeap.size = 0;
MaxHeap maxHeap;
maxHeap.size = 0;

// Insert elements into Min Heap


insertMinHeap(&minHeap, 3);
insertMinHeap(&minHeap, 2);
insertMinHeap(&minHeap, 15);
insertMinHeap(&minHeap, 5);
insertMinHeap(&minHeap, 4);
insertMinHeap(&minHeap, 45);

printf("Min Heap:\n");
displayMinHeap(&minHeap);

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

// Delete element from Min Heap


deleteMin(&minHeap, 2);
printf("Min Heap after deleting 2:\n");
displayMinHeap(&minHeap);

// Insert elements into Max Heap


insertMaxHeap(&maxHeap, 3);
insertMaxHeap(&maxHeap, 2);
insertMaxHeap(&maxHeap, 15);
insertMaxHeap(&maxHeap, 5);
insertMaxHeap(&maxHeap, 4);
insertMaxHeap(&maxHeap, 45);

printf("Max Heap:\n");
displayMaxHeap(&maxHeap);

// Delete element from Max Heap


deleteMax(&maxHeap, 15);
printf("Max Heap after deleting 15:\n");
displayMaxHeap(&maxHeap);

return 0;
}

4.Implement BFT and DFT for given graph, when graph is represented by
a) Adjacency Matrix b) Adjacency Lists

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

#define MAX_VERTICES 100

typedef struct GraphMatrix {


int numVertices;
int adjMatrix[MAX_VERTICES][MAX_VERTICES];
} GraphMatrix;

void initGraphMatrix(GraphMatrix* graph, int numVertices) {


graph->numVertices = numVertices;
for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
graph->adjMatrix[i][j] = 0;
}
}

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

void addEdgeMatrix(GraphMatrix* graph, int src, int dest) {


graph->adjMatrix[src][dest] = 1;
graph->adjMatrix[dest][src] = 1; // For undirected graph
}

void BFTMatrix(GraphMatrix* graph, int startVertex) {


int visited[MAX_VERTICES] = {0};
int queue[MAX_VERTICES];
int front = 0, rear = 0;

visited[startVertex] = 1;
queue[rear++] = startVertex;

while (front < rear) {


int currentVertex = queue[front++];
printf("%d ", currentVertex);

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


if (graph->adjMatrix[currentVertex][i] == 1 && !visited[i]) {
queue[rear++] = i;
visited[i] = 1;
}
}
}
}

void DFTMatrixUtil(GraphMatrix* graph, int vertex, int* visited) {


visited[vertex] = 1;
printf("%d ", vertex);

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


if (graph->adjMatrix[vertex][i] == 1 && !visited[i]) {
DFTMatrixUtil(graph, i, visited);
}
}
}

void DFTMatrix(GraphMatrix* graph, int startVertex) {


int visited[MAX_VERTICES] = {0};
DFTMatrixUtil(graph, startVertex, visited);
}

typedef struct Node {


int vertex;
struct Node* next;
} Node;

typedef struct GraphList {


int numVertices;
Node* adjLists[MAX_VERTICES];
} GraphList;

Node* createNode(int vertex) {


Node* newNode = (Node*)malloc(sizeof(Node));
newNode->vertex = vertex;
newNode->next = NULL;
return newNode;
}

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

void initGraphList(GraphList* graph, int numVertices) {


graph->numVertices = numVertices;
for (int i = 0; i < numVertices; i++) {
graph->adjLists[i] = NULL;
}
}

void addEdgeList(GraphList* graph, int src, int dest) {


Node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;

newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode; // For undirected graph
}

void BFTList(GraphList* graph, int startVertex) {


int visited[MAX_VERTICES] = {0};
int queue[MAX_VERTICES];
int front = 0, rear = 0;

visited[startVertex] = 1;
queue[rear++] = startVertex;

while (front < rear) {


int currentVertex = queue[front++];
printf("%d ", currentVertex);

Node* temp = graph->adjLists[currentVertex];


while (temp) {
int adjVertex = temp->vertex;
if (!visited[adjVertex]) {
queue[rear++] = adjVertex;
visited[adjVertex] = 1;
}
temp = temp->next;
}
}
}

void DFTListUtil(GraphList* graph, int vertex, int* visited) {


visited[vertex] = 1;
printf("%d ", vertex);

Node* temp = graph->adjLists[vertex];


while (temp) {
int adjVertex = temp->vertex;
if (!visited[adjVertex]) {
DFTListUtil(graph, adjVertex, visited);
}
temp = temp->next;
}
}

void DFTList(GraphList* graph, int startVertex) {


int visited[MAX_VERTICES] = {0};
DFTListUtil(graph, startVertex, visited);

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

int main() {
// Example for Adjacency Matrix
GraphMatrix graphMatrix;
initGraphMatrix(&graphMatrix, 5);
addEdgeMatrix(&graphMatrix, 0, 1);
addEdgeMatrix(&graphMatrix, 0, 4);
addEdgeMatrix(&graphMatrix, 1, 2);
addEdgeMatrix(&graphMatrix, 1, 3);
addEdgeMatrix(&graphMatrix, 1, 4);
addEdgeMatrix(&graphMatrix, 2, 3);
addEdgeMatrix(&graphMatrix, 3, 4);

printf("BFT for Adjacency Matrix:\n");


BFTMatrix(&graphMatrix, 0);
printf("\nDFT for Adjacency Matrix:\n");
DFTMatrix(&graphMatrix, 0);

// Example for Adjacency List


GraphList graphList;
initGraphList(&graphList, 5);
addEdgeList(&graphList, 0, 1);
addEdgeList(&graphList, 0, 4);
addEdgeList(&graphList, 1, 2);
addEdgeList(&graphList, 1, 3);
addEdgeList(&graphList, 1, 4);
addEdgeList(&graphList, 2, 3);
addEdgeList(&graphList, 3, 4);

printf("\n\nBFT for Adjacency List:\n");


BFTList(&graphList, 0);
printf("\nDFT for Adjacency List:\n");
DFTList(&graphList, 0);

return 0;
}

5.Write a program for finding the biconnected components in a given graph.


#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_VERTICES 100

typedef struct Node {


int vertex;
struct Node* next;
} Node;

typedef struct Graph {


int numVertices;

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

Node* adjLists[MAX_VERTICES];
bool visited[MAX_VERTICES];
int disc[MAX_VERTICES];
int low[MAX_VERTICES];
int parent[MAX_VERTICES];
bool ap[MAX_VERTICES]; // Articulation points
} Graph;

Node* createNode(int vertex) {


Node* newNode = (Node*)malloc(sizeof(Node));
newNode->vertex = vertex;
newNode->next = NULL;
return newNode;
}

void initGraph(Graph* graph, int numVertices) {


graph->numVertices = numVertices;
for (int i = 0; i < numVertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = false;
graph->disc[i] = -1;
graph->low[i] = -1;
graph->parent[i] = -1;
graph->ap[i] = false;
}
}

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


Node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;

newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode; // For undirected graph
}
typedef struct Stack {

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

int top;
int array[MAX_VERTICES];
int count;
} Stack;

void initStack(Stack* stack) {


stack->top = -1;
stack->count = 0;
}

bool isStackEmpty(Stack* stack) {


return stack->top == -1;
}

void push(Stack* stack, int item) {


stack->array[++stack->top] = item;
}

int pop(Stack* stack) {


if (isStackEmpty(stack)) {
return -1;
}
return stack->array[stack->top--];
}
void BCCUtil(Graph* graph, int u, Stack* stack, int* time) {
static int discTime = 0;
graph->visited[u] = true;
graph->disc[u] = graph->low[u] = ++discTime;
int children = 0;

Node* temp = graph->adjLists[u];


while (temp) {
int v = temp->vertex;
if (!graph->visited[v]) {
children++;
graph->parent[v] = u;
push(stack, u);

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

push(stack, v);
BCCUtil(graph, v, stack, time);

graph->low[u] = (graph->low[u] < graph->low[v]) ? graph->low[u] : graph->low[v];

if ((graph->parent[u] == -1 && children > 1) || (graph->parent[u] != -1 && graph->low[v] >=


graph->disc[u])) {
printf("Biconnected Component: ");
while (stack->array[stack->top] != u || stack->array[stack->top - 1] != v) {
printf("%d ", pop(stack));
}
printf("%d %d\n", pop(stack), pop(stack));
}
} else if (v != graph->parent[u] && graph->disc[v] < graph->disc[u]) {
graph->low[u] = (graph->low[u] < graph->disc[v]) ? graph->low[u] : graph->disc[v];
push(stack, u);
push(stack, v);
}
temp = temp->next;
}
}

void findBCC(Graph* graph) {


Stack stack;
initStack(&stack);
int time = 0;
for (int i = 0; i < graph->numVertices; i++) {
if (!graph->visited[i]) {
BCCUtil(graph, i, &stack, &time);
}
}

if (!isStackEmpty(&stack)) {
printf("Biconnected Component: ");
while (!isStackEmpty(&stack)) {
printf("%d ", pop(&stack));
}
printf("\n");

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

}
}
int main() {
Graph graph;
initGraph(&graph, 5);

addEdge(&graph, 0, 1);
addEdge(&graph, 0, 2);
addEdge(&graph, 1, 2);
addEdge(&graph, 1, 3);
addEdge(&graph, 3, 4);
addEdge(&graph, 2, 3);

printf("Biconnected Components in the graph:\n");


findBCC(&graph);

return 0;
}

6.Implement Quick sort and Merge sort and observe the execution time for various
input sizes (Average, Worst and Best cases).
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

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


int temp = *a;
*a = *b;
*b = temp;
}

int partition(int arr[], int low, int high) {


int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
swap(&arr[i], &arr[j]);

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

}
}
swap(&arr[i + 1], &arr[high]);
return i + 1;
}

void quickSort(int arr[], int low, int high) {


if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
void merge(int arr[], int l, int m, int r) {
int n1 = m - l + 1;
int n2 = r - m;

int L[n1], R[n2];

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


L[i] = arr[l + i];
for (int j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];

int i = 0, j = 0, k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}

while (i < n1) {

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

arr[k] = L[i];
i++;
k++;
}

while (j < n2) {


arr[k] = R[j];
j++;
k++;
}
}

void mergeSort(int arr[], int l, int r) {


if (l < r) {
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}

7.Compare the performance of Single Source Shortest Paths using Greedy method when
the graph is represented by adjacency matrix and adjacency lists.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits.h>
#include <time.h>

#define MAX_VERTICES 100


#define INF INT_MAX

typedef struct GraphMatrix {


int numVertices;
int adjMatrix[MAX_VERTICES][MAX_VERTICES];
} GraphMatrix;

void initGraphMatrix(GraphMatrix* graph, int numVertices) {

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

graph->numVertices = numVertices;
for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
graph->adjMatrix[i][j] = INF;
}
}
}

void addEdgeMatrix(GraphMatrix* graph, int src, int dest, int weight) {


graph->adjMatrix[src][dest] = weight;
graph->adjMatrix[dest][src] = weight; // For undirected graph
}

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


int min = INF, min_index;

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


if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;

return min_index;
}

void dijkstraMatrix(GraphMatrix* graph, int src) {


int V = graph->numVertices;
int dist[V];
bool sptSet[V];

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


dist[i] = INF, sptSet[i] = false;

dist[src] = 0;

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


int u = minDistance(dist, sptSet, V);
sptSet[u] = true;

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

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


if (!sptSet[v] && graph->adjMatrix[u][v] != INF && dist[u] != INF
&& dist[u] + graph->adjMatrix[u][v] < dist[v])
dist[v] = dist[u] + graph->adjMatrix[u][v];
}
}
typedef struct Node {
int vertex;
int weight;
struct Node* next;
} Node;

typedef struct GraphList {


int numVertices;
Node* adjLists[MAX_VERTICES];
} GraphList;

Node* createNode(int vertex, int weight) {


Node* newNode = (Node*)malloc(sizeof(Node));
newNode->vertex = vertex;
newNode->weight = weight;
newNode->next = NULL;
return newNode;
}

void initGraphList(GraphList* graph, int numVertices) {


graph->numVertices = numVertices;
for (int i = 0; i < numVertices; i++) {
graph->adjLists[i] = NULL;
}
}

void addEdgeList(GraphList* graph, int src, int dest, int weight) {


Node* newNode = createNode(dest, weight);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

newNode = createNode(src, weight);


newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode; // For undirected graph
}

int minDistanceList(int dist[], bool sptSet[], int V) {


int min = INF, min_index;

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


if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;

return min_index;
}

void dijkstraList(GraphList* graph, int src) {


int V = graph->numVertices;
int dist[V];
bool sptSet[V];

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


dist[i] = INF, sptSet[i] = false;

dist[src] = 0;

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


int u = minDistanceList(dist, sptSet, V);
sptSet[u] = true;

Node* temp = graph->adjLists[u];


while (temp != NULL) {
int v = temp->vertex;
if (!sptSet[v] && dist[u] != INF && dist[u] + temp->weight < dist[v])
dist[v] = dist[u] + temp->weight;
temp = temp->next;
}
}

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

}
void generateGraphMatrix(GraphMatrix* graph, int numEdges) {
for (int i = 0; i < numEdges; i++) {
int src = rand() % graph->numVertices;
int dest = rand() % graph->numVertices;
int weight = rand() % 100 + 1;
addEdgeMatrix(graph, src, dest, weight);
}
}

void generateGraphList(GraphList* graph, int numEdges) {


for (int i = 0; i < numEdges; i++) {
int src = rand() % graph->numVertices;
int dest = rand() % graph->numVertices;
int weight = rand() % 100 + 1;
addEdgeList(graph, src, dest, weight);
}
}

int main() {
int sizes[] = {10, 50, 100, 500, 1000};
int numSizes = sizeof(sizes) / sizeof(sizes[0]);
srand(time(0));

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


int size = sizes[i];
int numEdges = size * (size - 1) / 2; // Dense graph

GraphMatrix graphMatrix;
initGraphMatrix(&graphMatrix, size);
generateGraphMatrix(&graphMatrix, numEdges);

GraphList graphList;
initGraphList(&graphList, size);
generateGraphList(&graphList, numEdges);

// Timing Dijkstra using Adjacency Matrix

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

clock_t start = clock();


dijkstraMatrix(&graphMatrix, 0);
clock_t end = clock();
double matrixTime = ((double)(end - start)) / CLOCKS_PER_SEC;

// Timing Dijkstra using Adjacency List


start = clock();
dijkstraList(&graphList, 0);
end = clock();
double listTime = ((double)(end - start)) / CLOCKS_PER_SEC;

printf("Graph Size: %d\n", size);


printf("Dijkstra using Adjacency Matrix: %f seconds\n", matrixTime);
printf("Dijkstra using Adjacency List: %f seconds\n", listTime);
printf("\n");
}

return 0;
}

8.Implement Job Sequencing with deadlines using Greedy strategy.


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

typedef struct Job {


char id; // Job Id
int deadline; // Deadline of job
int profit; // Profit if job is completed before or on deadline
} Job;

// A utility function to compare two jobs based on profit


int compare(const void* a, const void* b) {
Job* jobA = (Job*)a;
Job* jobB = (Job*)b;
return jobB->profit - jobA->profit;
}

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

// A utility function to find the maximum deadline in the given array of jobs
int findMaxDeadline(Job jobs[], int n) {
int maxDeadline = jobs[0].deadline;
for (int i = 1; i < n; i++) {
if (jobs[i].deadline > maxDeadline) {
maxDeadline = jobs[i].deadline;
}
}
return maxDeadline;
}

// A utility function to print the job sequence


void printJobSequence(Job jobs[], int n) {
for (int i = 0; i < n; i++) {
printf("%c ", jobs[i].id);
}
printf("\n");
}
void jobSequencingWithDeadlines(Job jobs[], int n) {
// Sort all jobs in decreasing order of profit
qsort(jobs, n, sizeof(Job), compare);

// Find the maximum deadline


int maxDeadline = findMaxDeadline(jobs, n);

// Create an array to store the result (sequence of jobs)


char result[maxDeadline + 1];
for (int i = 0; i <= maxDeadline; i++) {
result[i] = '\0'; // Initialize all slots to empty
}

// Create an array to keep track of free time slots


int slot[maxDeadline + 1];
for (int i = 0; i <= maxDeadline; i++) {
slot[i] = 0; // Initialize all slots to free
}

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

// Iterate through all given jobs


for (int i = 0; i < n; i++) {
// Find a free slot for this job (Note that we start from the last possible slot)
for (int j = jobs[i].deadline; j > 0; j--) {
if (slot[j] == 0) {
result[j] = jobs[i].id; // Add this job to result
slot[j] = 1; // Mark this slot as occupied
break;
}
}
}

// Print the result


printf("Job sequence is: ");
for (int i = 1; i <= maxDeadline; i++) {
if (result[i] != '\0') {
printf("%c ", result[i]);
}
}
printf("\n");
}
int main() {
Job jobs[] = { {'a', 2, 100}, {'b', 1, 19}, {'c', 2, 27}, {'d', 1, 25}, {'e', 3, 15} };
int n = sizeof(jobs) / sizeof(jobs[0]);

printf("Given jobs:\n");
for (int i = 0; i < n; i++) {
printf("Job %c: Deadline = %d, Profit = %d\n", jobs[i].id, jobs[i].deadline, jobs[i].profit);
}

jobSequencingWithDeadlines(jobs, n);

return 0;
}

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

9.Write a program to solve 0/1 Knapsack problem Using Dynamic Programming


 C program that solves the 0/1 Knapsack problem using dynamic programming
#include <stdio.h>

// A utility function to return the maximum of two integers


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

// Function to solve 0/1 Knapsack problem using dynamic programming


int knapsack(int W, int wt[], int val[], int n) {
int i, w;
int K[n + 1][W + 1];

// Build table K[][] in bottom-up manner


for (i = 0; i <= n; i++) {
for (w = 0; w <= W; w++) {
if (i == 0 || w == 0) {
K[i][w] = 0;
} else if (wt[i - 1] <= w) {
K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]);
} else {
K[i][w] = K[i - 1][w];
}
}
}

return K[n][W];
}

// Driver program to test the knapsack function


int main() {
int val[] = {60, 100, 120};
int wt[] = {10, 20, 30};
int W = 50;
int n = sizeof(val) / sizeof(val[0]);

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

printf("Maximum value in Knapsack = %d\n", knapsack(W, wt, val, n));

return 0;
}

10.Implement N-Queens Problem Using Backtracking.


 C program to solve the N-Queens problem using backtracking
#include <stdio.h>
#include <stdbool.h>

#define N 8 // You can change N to any number to solve the N-Queens problem for different
board sizes

// A utility function to print the solution


void printSolution(int board[N][N]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf(" %d ", board[i][j]);
}
printf("\n");
}
}

// A utility function to check if a queen can be placed on board[row][col]


bool isSafe(int board[N][N], int row, int col) {
int i, j;

// Check this row on left side


for (i = 0; i < col; i++) {
if (board[row][i]) {
return false;
}
}

// Check upper diagonal on left side


for (i = row, j = col; i >= 0 && j >= 0; i--, j--) {
if (board[i][j]) {
return false;

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

}
}

// Check lower diagonal on left side


for (i = row, j = col; j >= 0 && i < N; i++, j--) {
if (board[i][j]) {
return false;
}
}

return true;
}

// A recursive utility function to solve N-Queens problem


bool solveNQUtil(int board[N][N], int col) {
// Base case: If all queens are placed then return true
if (col >= N) {
return true;
}

// Consider this column and try placing this queen in all rows one by one
for (int i = 0; i < N; i++) {
// Check if the queen can be placed on board[i][col]
if (isSafe(board, i, col)) {
// Place this queen in board[i][col]
board[i][col] = 1;

// Recur to place rest of the queens


if (solveNQUtil(board, col + 1)) {
return true;
}

// If placing queen in board[i][col] doesn't lead to a solution, then remove queen from
board[i][col]
board[i][col] = 0; // Backtrack
}
}

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

// If the queen cannot be placed in any row in this column col, then return false
return false;
}

// This function solves the N-Queens problem using Backtracking. It mainly uses solveNQUtil()
to solve the problem. It returns false if queens cannot be placed, otherwise, it returns true and
prints the placement of queens in the form of 1s. Please note that there may be more than one
solutions, this function prints one of the feasible solutions.
bool solveNQ() {
int board[N][N] = {0};

if (!solveNQUtil(board, 0)) {
printf("Solution does not exist");
return false;
}

printSolution(board);
return true;
}

// Driver program to test the above functions


int main() {
solveNQ();
return 0;
}

Use Backtracking strategy to solve 0/1 Knapsack problem.


#include <stdio.h>

// A utility function to return the maximum of two integers


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

// A utility function to print the solution


void printSolution(int n, int items[], int included[]) {
printf("Items included in the knapsack are:\n");
for (int i = 0; i < n; i++) {

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

if (included[i]) {
printf("Item %d\n", items[i]);
}
}
}

// Backtracking function to solve 0/1 Knapsack problem


void knapsackBacktracking(int W, int wt[], int val[], int n, int idx, int curWeight, int curValue, int
*maxValue, int included[], int solution[]) {
if (idx == n) {
if (curValue > *maxValue) {
*maxValue = curValue;
for (int i = 0; i < n; i++) {
solution[i] = included[i];
}
}
return;
}

// Include the current item


if (curWeight + wt[idx] <= W) {
included[idx] = 1;
knapsackBacktracking(W, wt, val, n, idx + 1, curWeight + wt[idx], curValue + val[idx],
maxValue, included, solution);
included[idx] = 0;
}

// Exclude the current item


knapsackBacktracking(W, wt, val, n, idx + 1, curWeight, curValue, maxValue, included,
solution);
}

// Driver program to test the knapsackBacktracking function


int main() {
int val[] = {60, 100, 120};
int wt[] = {10, 20, 30};
int W = 50;
int n = sizeof(val) / sizeof(val[0]);

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

int maxValue = 0;
int included[n];
int solution[n];
for (int i = 0; i < n; i++) {
included[i] = 0;
solution[i] = 0;
}

knapsackBacktracking(W, wt, val, n, 0, 0, 0, &maxValue, included, solution);

printf("Maximum value in Knapsack = %d\n", maxValue);


printSolution(n, wt, solution);

return 0;
}

12.Implement Travelling Sales Person problem using Branch and Bound approach
C program to solve the TSP using the Branch and Bound approach
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <stdbool.h>

#define N 4 // Change this value to solve TSP for different numbers of cities
// Function to print the solution
void printSolution(int path[]) {
printf("Path: ");
for (int i = 0; i < N; i++) {
printf("%d ", path[i]);
}
printf("%d\n", path[0]);
}

// Function to calculate the cost of a path


int calculateCost(int graph[N][N], int path[]) {
int cost = 0;

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

for (int i = 0; i < N - 1; i++) {


cost += graph[path[i]][path[i + 1]];
}
cost += graph[path[N - 1]][path[0]]; // Returning to the starting city
return cost;
}

// Function to copy temporary solution to the final solution


void copyToFinal(int curr_path[], int final_path[]) {
for (int i = 0; i < N; i++) {
final_path[i] = curr_path[i];
}
final_path[N] = curr_path[0];
}
// Function to find the minimum edge cost having an end at the vertex i
int firstMin(int graph[N][N], int i) {
int min = INT_MAX;
for (int k = 0; k < N; k++) {
if (graph[i][k] < min && i != k) {
min = graph[i][k];
}
}
return min;
}

// Function to find the second minimum edge cost having an end at the vertex i
int secondMin(int graph[N][N], int i) {
int first = INT_MAX, second = INT_MAX;
for (int j = 0; j < N; j++) {
if (i == j) continue;
if (graph[i][j] <= first) {
second = first;
first = graph[i][j];
} else if (graph[i][j] <= second && graph[i][j] != first) {
second = graph[i][j];
}
}

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

return second;
}

// Function to solve the TSP problem using Branch and Bound


void TSP(int graph[N][N], int curr_bound, int curr_weight, int level, int curr_path[], bool
visited[], int final_path[], int *final_res) {
if (level == N) {
if (graph[curr_path[level - 1]][curr_path[0]] != 0) {
int curr_res = curr_weight + graph[curr_path[level - 1]][curr_path[0]];
if (curr_res < *final_res) {
copyToFinal(curr_path, final_path);
*final_res = curr_res;
}
}
return;
}

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


if (graph[curr_path[level - 1]][i] != 0 && visited[i] == false) {
int temp = curr_bound;
curr_weight += graph[curr_path[level - 1]][i];

if (level == 1) {
curr_bound -= ((firstMin(graph, curr_path[level - 1]) + firstMin(graph, i)) / 2);
} else {
curr_bound -= ((secondMin(graph, curr_path[level - 1]) + firstMin(graph, i)) / 2);
}

if (curr_bound + curr_weight < *final_res) {


curr_path[level] = i;
visited[i] = true;
TSP(graph, curr_bound, curr_weight, level + 1, curr_path, visited, final_path,
final_res);
}

curr_weight -= graph[curr_path[level - 1]][i];


curr_bound = temp;

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

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


visited[k] = false;
}
for (int j = 0; j <= level - 1; j++) {
visited[curr_path[j]] = true;
}
}
}
}
int main() {
int graph[N][N] = {
{0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}
};

int curr_path[N + 1];


int final_path[N + 1];
bool visited[N];

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


visited[i] = false;
curr_path[i] = -1;
}

int curr_bound = 0;
for (int i = 0; i < N; i++) {
curr_bound += (firstMin(graph, i) + secondMin(graph, i));
}

curr_bound = (curr_bound & 1) ? curr_bound / 2 + 1 : curr_bound / 2;

visited[0] = true;
curr_path[0] = 0;

int final_res = INT_MAX;

Downloaded by Hanumantharao Murukutla ([email protected])


lOMoARcPSD|15581981

TSP(graph, curr_bound, 0, 1, curr_path, visited, final_path, &final_res);

printf("Minimum cost : %d\n", final_res);


printSolution(final_path);

return 0;
}

Downloaded by Hanumantharao Murukutla ([email protected])

You might also like