0% found this document useful (0 votes)
20 views48 pages

02 Merged

Uploaded by

blesswinsj12
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)
20 views48 pages

02 Merged

Uploaded by

blesswinsj12
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/ 48

SNS COLLEGE OF TECHNOLOGY

(AUTONOMOUS)
COIMBATORE-35

DEPARTMENT OF COMPUTER APPLICATIONS

23CAP601–DATA STRUCTURES AND ALGORITHMS LABORATORY

PRACTICAL RECORD

NAME :
REGISTER NO :
DEPARTMENT :
SEMESTER :
SNS COLLEGE OF TECHNOLOGY
(AUTONOMOUS)

COIMBATORE-35

DEPARTMENT OF COMPUTER APPLICATIONS

23CAP601–DATA STRUCTURES AND ALGORITHMS LABORATORY

Register No:

Certified that this is a bonafide record of work done by the


candidate Mr / Ms …………………………………………….
of First Year Master of Computer Applications in 23CAP601 –
Data Structures and Algorithms Laboratory during the
academic year 2024- 2025.

Signature of Lab In-Charge Head of the Department

Submitted for the practical examination held on ……………………

Internal Examiner External Examiner


INDEX
S.No DATE Name of the Program PAGE N0 Practical Record Viva Total Signature
Class, Book Voce (50)
Performance, Assessme (10)
Assessment nt
(25) (15)

1 07.10.2024 Strassen’s Matrix


Multiplication

2 28.10.2024 Implementation of
Stack

3 04.11.2024 Implementation of
Queue

4 11.11.2024 Implementation of
Merge Sort

5 15.11.2024 Implementation of
Quick Sort

6 25.11.2024 Implementation of
Binary Tree
Traversal

7 10.12.2024 Implementation of
DFS

8 16.12.2024 Implementation of
BFS

9 23.12.2024 Implementation of
Prim’s Algorithm

10 24.12.2024 Implementation of
Knapsack Algorithm

11 30.12.2024 Implementation of
Subset Sum Problem

12 06.01.202 Implementation of
5 Travelling
Salesperson Problem

1
Ex.No: 1 STRASSENN’S MATRIX MULTIPLICATION
Date : 07.10.2024

AIM :
To find the matrix multiplication using Strassenn’s Matrix.

ALGORITHM :
STEP1:Start the process

STEP2:Declare the array variables a[2][2],b[2][2],c[2][2].

STEP 3 : Calculate Strassen ’s matrix using given

formula.

Strassen’s Matrix
A B E F
a= ] b=[ ]
[
C D G H
M1=(A+B)*(E+H)
M2=(C+D)*E
M3=A*(F-H)
M4=D*(G-E)
M5=(A+B)*H
M6=(C-A)*(E+F)
M7=(B-D)*(G+H)
c[0][0]=M1+M4-M5+M7
c[0][1]=M3+M5
c[1][0]=M2+M4
c[0][0]=M1-M2+M3+M6

STEP4: Print the Result matrixc[2][2].

STEP 5: Stop the process .


CODING :

#include <stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int a[2][2], b[2][2], c[2][2], m1, m2, m3, m4, m5, m6, m7, i, j;
printf("Enter elements of 2x2 Matrix A:\n");
for (i = 0; i < 2; i++) for (j = 0; j < 2; j++) scanf("%d", &a[i][j]);
printf("Enter elements of 2x2 Matrix B:\n");
for (i = 0; i < 2; i++) for (j = 0; j < 2; j++) scanf("%d", &b[i][j]);
m1 = (a[0][0] + a[1][1]) * (b[0][0] + b[1][1]);
m2 = (a[1][0] + a[1][1]) * b[0][0];
m3 = a[0][0] * (b[0][1] - b[1][1]);
m4 = a[1][1] * (b[1][0] - b[0][0]);
m5 = (a[0][0] + a[0][1]) * b[1][1];
m6 = (a[1][0] - a[0][0]) * (b[0][0] + b[0][1]);
m7 = (a[0][1] - a[1][1]) * (b[1][0] + b[1][1]);
c[0][0] = m1 + m4 - m5 + m7;
c[0][1] = m3 + m5;
c[1][0] = m2 + m4;
c[1][1] = m1 - m2 + m3 + m6;
printf("Resultant Matrix C:\n");
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
printf("%d\t", c[i][j]);
printf("\n");
}
getch();
}
OUTPUT :

RESULT :

Calculated the matrix multiplication using Strassen's matrix multiplication.


ExNo: 2
Date : 28.10.2024 IMPLEMENTING STACK USING ARRAY
YYYYAAAAAAAAAAAARRAY

AIM :

Write a C program for implementation of stack using array

ALGORITHM :

STEP1: Start the process.

STEP2: Define the function prototype for push(), pop() and display().

STEP3: Declare the following variables as integer:top, stack[10], num, choice, i and assign value -1to top.

STEP4: Read size of stack element using scanf.

STEP5: Use switch case to get the choice to perform push().pop(),display() function upto

the choice value 4.

STEP6: If the value of choice=1 then call push function to do the following operation.

a) Check if top-n then stack is full.

b) Else get an item from the key board and push into stack.

c) Repeat the step until getting choice value=1.

STEP7: lf the value of choice-2 then call pop function and do the following task.

a) Check if top-1 then the stack is empty.

b) Else pop an element at the top of stack.

c) Repeatstep7untilthevalueofchoice-2.

STEP8: If the value of choice-3 then display all the elements in stack.
STEP9: If the value of choice 4 then exit.
STEP10: Stop the process.
CODING :

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void push();
void pop();
void display();
int top=1,stack[5],t,choice,n,i;
void main()
{
clrscr();
printf("enter stack size:\n");
scanf("%d",&n);
do
{
printf("n1.push\n2.pop\n3.display\n4.exit\n");
printf("Enter your choice\n\n");
scanf("%d",&choice);
switch(choice)
{
case 1:push();
break;
case 2:pop();
break;
case 3:display();
break;
case 4:exit(0);
break;
default:printf("Enter crt choice");
}
}
while(choice!=4);
getch();
}
void push()
{
if(top==n-1)
{
printf("Stack is full\n");
}
else
{
printf("Enter stack value\n");
scanf("%d",&t);
top=top+1;
stack[top]=t;
}
}
void pop()
{
if(top==-1)
{
printf("\n Stack is empty\n");
}
else
{
top=top-1;
}
}
void display()
{
printf("\n Stack value\n");
for(i=top;i>=0;i--)
{
printf("%d\n",stack[i]);
}
}

OUTPUT :

RESULT :

Thus the above Stack program using array is successfully completed.


ExNo: 3
Date : 04.11.2024 IMPLEMENTATION OF QUEUE

AIM :
Write a C program for implemention of queue using array.

ALGORITHM :
STEP1 : Start the process.
STEP2: Define the function prototype for insert(), remove() and display().
STEP3: Declare the following variables as integer:frontrear, queue[10], num, choice, i and assign value
-1 to front and rear.
STEP4: Read size of queue element using scanf.
STEP5: Uses witch case to get the choice to perform insert(), remove(), display() function upto the
choice value 4.
STEP6: If the value of choice-1 then call insert function to do the following operation.
a) Check if rear num-1 then queue is full.
b) Else get an item from the key board and insert into queue.
c) Repeat the step until getting choice value-1.
STEP7: lf the value of choice-2 then call remove function and do the following task.
d) Check if front1or front rear then the queue is empty.
e) Else delete an element from the queue.
f) Repeat step7 until the value of choice-2.
STEP8: If the value of choice3 then display all the elements in queue.
STEP 9: lf the value of choice 4 then exit.
STEP10: Stop the process.
CODING :

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void insert();
void delete_q();
void display();
int rear=-1,front=-1,queue[5],choice,n,i,t;
void main()
{
clrscr();
printf("Enter the queue size\n");
scanf("%d",&n);
do
{
printf("1.insert \n 2.delete \n 3.display \n 4.exit \n");
printf("Enter your choice: \n");
scanf("%d",&choice);
switch(choice)
{
case 1:insert();
break;
case 2:delete_q();
break;
case 3:display();
break;
case 4:exit(0);
break;
default:printf("enter the correct choice\n");
}
}
while(choice!= 4);
getch();
}
void insert()
{
if(rear==n-1)
{
printf("queue is full\n");
}
else
{
printf("Enter the queue value\n");
scanf("%d",&t);
front=0;
rear=rear+1;
queue[rear]=t;
}
}
void delete_q()
{
if(front==-1 | front>rear)
{
printf("\n queue is empty\n");
}
else
{
front=front+1;
}
}
void display()
{
if(front==-1 | front>rear){
printf("\n queue is empty \n");
}
else{
printf("\n queue value\n");
for(i=front;i<=rear;i++)
{
printf("%dd\t",queue[i]);
}
}
}
OUTPUT :
RESULT :
Thus the above Queue program using array is successfully completed.
Ex.No: 4
Date : 11.11.2023 IMPLEMENTATION OF MERGE SORT

AIM :
Write a C program to sort the set of elements using merge sort.

ALGORITHM :
STEP1:Start the process

STEP2:Declare the variables and function prototypes.

STEP3:Declare left and right var which will mark the extreme indices of the array.
STEP 4:Left will be assigned to 0 and right will be assigned to n-1.
STEP5:Find mid=(left + right)/2.

STEP6:Call merge Sort on(left, mid)and(mid+1,rear).

STEP7:Above will continue till left-right.


STEP8:Then we will call merge on the 2 sub problems.

STEP 9:Print the sorted lis.

STEP10:stop the process


CODING :

#include <stdio.h>
void mergesort(int a[], int i, int j);
void merge(int a[], int i1, int j1, int i2, int j2);
void main()
{
int a[30], n, i;
clrscr();
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter array elements: ");
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
mergesort(a, 0, n - 1);
printf("\nSorted Array: ");
for (i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
printf("\n");
getch();
}
void mergesort(int a[], int i, int j)
{
if (i < j)
{
int mid = (i + j) / 2;
mergesort(a, i, mid);
mergesort(a, mid + 1, j);
merge(a, i, mid, mid + 1, j);
}
}
void merge(int a[], int i1, int j1, int i2, int j2)
{
int temp[50];
int i = i1, j = i2, k = 0;
while (i <= j1 && j <= j2)
{
if (a[i] < a[j])
{
temp[k++] = a[i++];
}
else {
temp[k++] = a[j++];
}
}
while (i <= j1)
{
temp[k++] = a[i++];
}
while (j <= j2)
{
temp[k++] = a[j++];
}
for (i = i1, j = 0; i <= j2; i++, j++)
{
a[i] = temp[j];
}
}
OUTPUT :

RESULT :
Thus the above merge sort program has been completed successfully.
Ex.No: 5
IMPLEMENTATION OF QUICK SORT
Date : 15.11.2024

AIM :
Write a C program to sort the set of elements using quick sort.

ALGORITHM :
STEP1:Start the process.

STEP2:Declare function prototype and integer.

STEP3: Read the size of an element.

STEP4: Read the number of all elements.


STEP5:Do the following function recursively.

a) Consider the first element of the list as a Pivot value.

b) Define two variable i and j and set i and j to first and last element of respective list.

c) Increment i until list[i]>pivot then stop.

d) Decrement j unt i list[j]>pivot then stop.

e) If i<j then exchange list[i] and list[j].

f) Repeat step c, d & e until i>j.

g) Exchange the pivot element with list[j] element.


STEP6: Display the sorted list.
STEP8:Stop the process.
CODING :
#include<stdio.h>
#include<conio.h>
void quicksort(int quick[], int low, int high)
{
int pivot, i, j, temp;
if (low < high)
{
pivot = quick[high];
i = low - 1;
for (j = low; j < high; j++)
{
if (quick[j] <= pivot)
{
i++;
temp = quick[i];
quick[i] = quick[j];
quick[j] = temp;
}
}
temp = quick[i + 1];
quick[i + 1] = quick[high];
quick[high] = temp;
quicksort(quick, low, i);
quicksort(quick, i + 2, high);
}
}

void main()
{
int quick[10], n, i;
clrscr();
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter the values: ");
for (i = 0; i < n; i++)
{
scanf("%d", &quick[i]);
}
quicksort(quick, 0, n - 1);
printf("\nSorted Elements: \n");
for (i = 0; i < n; i++)
{
printf("%d\t", quick[i]);
}
printf("\n");
getch();
}
OUTPUT :

RESULT :
Thus the above quick sort program successfully completed.
Ex.No: 6
Date : 25.11.2024 IMPLEMENTATION OF BINARY TREE TRAVERSAL

AIM :
Write a C program to perform binary tree traversals.

ALGORITHM :
Algorithm for Traversal of Binary Tree (Inorder, Preorder and Postorder)

STEP1:Start the process.

STEP2:Algorithm for in-order traversal.

a) Repeat Steps 2 to while.

TREE!=NULL.
b)INORDER(TREE LEFT).

c) Write TREE DATA.

d) INORDER(TREERIGHT)

[ENDOFLOOP].
e)END.
STEP3:Algorithm for pre-order traversal.

a) Repeat Steps 2 to 4 while TREE!=NULL.

b) Write TREE DATA.

c)REORDER(TREE

LEFT).

d)PREORDER(TREERIGHT)
[ENDOFLOOP].
e)END.
STEP4:Algorithm for post-order traversal.

a)Repeat Steps 2 to 4 while TREE!=NULL.


b)POSTORDER(TREE LEFT).

c) POSTORDER(TREERIGHT).

d) WriteTREEDATA

[ENDOFLOOP].

e)END.

STEP5:Stop the process.


CODING :

#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node* left;
struct Node* right;
};
struct Node* newNode(int data)
{
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = node->right = NULL;
return node;
}
void preorder(struct Node* root)
{
if (root != NULL)
{
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
}
void inorder(struct Node* root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}
void postorder(struct Node* root)
{
if (root != NULL)
{
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
}

void main()
{
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
clrscr();
printf("Preorder Traversal: ");
preorder(root);
printf("\n");
printf("Inorder Traversal: ");
inorder(root);
printf("\n");
printf("Postorder Traversal: ");
postorder(root);
printf("\n");
getch();
}
OUTPUT :

RESULT :

Thus the above binary tree traversals program is successfully completed.


Ex.No: 7
Date : 10.12.2024 IMPLEMENTATION OF DEPTH FIRST SEARCH

AIM :
Write a C program to perform DFS.

ALGORITHM :

STEP 1:Start the process.


STEP 2:Declare the variables
STEP 3:Declare the function.
STEP4:Read the number of vertices.

STEP5:Read the node value for each vertex.


STEP 6: Perform the step 7.
STEP 7: DFS

a) Start by putting any one of the graph’s vertices at the back of a queue.
b) Take the front item of the queue and add it to the visited list.
c) Create a list of that vertex’s adjacent nodes. Add the ones which aren’t in the visited list to
the back of the queue.
d) Keep repeating step2 and step3 until the queue is empty.
STEP 8: Print the output for DFS

STEP9: Stop the process.


CODING :

#include <stdio.h>
#include <conio.h>

int a[20][20], vis[20], stack[20], top = -1;


void push(int item);
int pop();
void dfs(int s, int n);

int main()
{
int n, i, j, s;
char c, dummy;
clrscr();
printf("ENTER THE NUMBER OF VERTICES: ");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
printf("ENTER 1 IF %d HAS AN EDGE WITH %d ELSE 0: ", i, j);
scanf("%d", &a[i][j]);
}
}

printf("THE ADJACENCY MATRIX IS\n");


for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
printf("%d ", a[i][j]);
}
printf("\n");
}

do {
for (i = 1; i <= n; i++)
{
vis[i] = 0;
}
printf("\nENTER THE SOURCE VERTEX: ");
scanf("%d", &s);
dfs(s, n);
printf("\nDO YOU WANT TO CONTINUE? (y/n): ");
scanf("%c", &dummy);
scanf("%c", &c);
} while (c == 'y' || c == 'Y');
getch();
return 0;
}
void dfs(int s, int n)
{
int i, k;
push(s);
vis[s] = 1;
while (top != -1)
{
k = pop();
printf("%d ", k);
for (i = 1; i <= n; i++)
{
if (a[k][i] == 1 && vis[i] == 0)
{
push(i);
vis[i] = 1;
}
}
}
}
void push(int item)
{
if (top == 19)
{
printf("Stack Overflow\n");
}
else
{
stack[++top] = item;
}
}
int pop()
{
if (top == -1)
{
return 0;
}
else
{
return stack[top--];
}
}
OUTPUT :

RESULT :
Thus the above Depth First Search program is successfully completed.
Ex.No: 8
Date : 16.12.2024 IMPLEMENTATION OF BREATH FIRST SEARCH

AIM :
Write a C program to perform BFS

ALGORITHM :

Step1: Start the process.

Step2:Declare the variables.

Step3:Declare the function.

Step4:Read the number of vertices.

Step5:Read the node value for each vertex.

Step6:Perform the step7.


Step7:BFS

a) Start by putting any one of the graph’s vertices on the top of the stack.
b) Take the top item of the stack and add it to the visited list.
c) Create a list of that vertex’s adjacent nodes. Add the ones which aren’t in the visited list
of the top of the stack.
d) Keep repeating step2 and step3 until the stack is empty.
e) Start by putting any one of the graph’s vertices at the back of a queue.

Step8:Print the output of BFS.


Step9:Stop the process.
CODING :

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

int q[20], top = -1, front = -1, rear = -1, a[20][20], vis[20], stack[20];
void add(int item);
int rmove();
void bfs(int s, int n);

void main() {
int n, i, s, ch, j;
char c, dummy;
system("cls");

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


scanf("%d", &n);
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
printf("Enter 1 if vertex %d has an edge with vertex %d, else 0: ", i, j);
scanf("%d", &a[i][j]);
}
}
printf("The adjacency matrix is:\n");
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
do {
for (i = 1; i <= n; i++) {
vis[i] = 0;
}

printf("\nEnter the source vertex: ");


scanf("%d", &s);
bfs(s, n);
printf("\nDo you want to perform BFS again? (y/n): ");
getch();
scanf("%c", &c);

} while (c == 'y' || c == 'Y');

getch();
}
void bfs(int s, int n) {
int p, i;

add(s);
vis[s] = 1;

p = rmove();
if (p != 0) {
printf("%d ", p);
}
while (p != 0) {
for (i = 1; i <= n; i++) {
if (a[p][i] != 0 && vis[i] == 0) {
add(i);
vis[i] = 1;
}
}
p = rmove();
if (p != 0) {
printf("%d ", p);
}
}
}
void add(int item) {
if (rear == 19) {
printf("Queue full\n");
} else {
if (rear == -1) {
q[++rear] = item;
front++;
} else {
q[++rear] = item;
}
}
}
int rmove() {
int k;
if (front > rear || front == -1) {
return 0;
} else {
k = q[front++];
return k;
}
}
OUTPUT :

RESULT :
Thus the above Breath First Search program is successfully completed.
Ex.No: 9
IMPLEMENTATION OF PRIM’S ALGORITHM
Date : 23.12.2024

AIM :
Write a C program to perform Prim’s algorithm.

ALGORITHM :

STEP 1: Start the process

STEP2:Declare the variables

STEP 3: Read the number of nodes


STEP4:Read the Adjacency matrices

STEP5:Randomly choose any vertex. Thevertex connecting to the edge having least weight is usually
selected.

STEP6:Find all the edges that connect the tree to new vertices.

STEP7:Find the least weight edge among those edges and include it in the existing tree.

STEP8:If including that edge creates a cycle, then reject that edge and look for the next least weight
edge.

STEP9:Keep repeating from step5 to step7 until all the vertices are included and Minimum Spanning
Tree (MST) is obtained.

STEP10:Print the minimum cost spanning tree.


STEP 11: stop the process.
CODING :

#include<stdio.h>
#include<conio.h>
inta,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost,cost[10][10];
void main()
{
clrscr();
printf("\nEnter the number of nodes:");
scanf("%d",&n);
printf("\nEnter the adjaceny matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
visited[1]=1;
printf("\n");
while(ne<n)
{
for(i=1,min=999;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]<min)
if(visited[i]!=0)
{
min=cost[i][j]; a=u=i;
b=v=j;
}

if(visited[u]==0||visited[v]==0)
{
printf("\nEdge%d:(%d%d)cost:%d",ne++,a,b,min);
mincost+=min;
visited[b]=1;
}
cost[a][b]=cost[b][a]=999;
}
printf("\nMinimum cost=%d",mincost);
getch();
}
OUTPUT :

RESULT :
Thus the above prim’s algorithm successfully completed,
IMPLEMENTATION OF KNAPSACK-DYNAMIC PROGRAMMING
Ex.No: 10
Date : 24.12.2024

AIM :
Write a C program to perform Knapsack-dynamic programming

ALGORITHM :
STEP1: Start the process

STEP2: Node root represents the initial state of the knapsack, where you have not selected any
package.

Total Value=0

The upper bound of the root node Upper Bound=M*Maximum unit cost.

STEP3: Node root will have child nodes corresponding to the ability to select the package with the
largest unit cost. For each node, you re-calculate the parameters:

Total Value=Total Value(old)+ number of selected packages value of each package.

M = M (old) - number of packages selected weight of each package.

Upper Bound=TotalValue+M(new)*The unit cost of the packaced to be considered next.

STEP4: In child nodes, you will prioritize branching for the node having the larger upper bound. The
children of this node correspond to the ability of selecting the next package having 1 large unit cost.
For each node, you must re-calculate the parameters Total Value, M, Upper Bound according to the
formula mentioned in step 2.

STEP 5: Repeat Step 3with the note: for nodes with upper bound is lower or equal values to the
temporary maximum cost of an option found, you do not need to branch for that node anymore.

STEP6: If all nodes are branched or cut off, the most expensive option is the one to look for.

STEP 7: Stop the process.


CODING :

#include<stdio.h>
#include<conio.h>
int max(int a, int b)
{
return (a > b) ? a : b;
}
int knapsack(int w, int wt[], int val[], int n)
{
if (n == 0 || w == 0)
{
return 0;
}

if (wt[n-1] > w)
{
return knapsack(w, wt, val, n-1);
}
else
{
return max(val[n-1] + knapsack(w - wt[n-1], wt, val, n-1),
knapsack(w, wt, val, n-1));
}
}
int main()
{
int val[] = {20, 25, 40};
int wt[] = {25, 20, 30};
int w = 50;
int n = sizeof(val) / sizeof(val[0]);
clrscr();
printf("Knapsack Problem\n");
printf("The Solution is%d", knapsack(w, wt, val, n));
getch();
return 0;
}
OUTPUT :

RESULT :
Thus the above Knapsack-dynamic programming is successfully completed.
Ex.No: 11
IMPLEMENTATION OF SUBSET SUM PROBLEM-BACKTRACKING
Date :30.12.2024

AIM :
Write a C program to perform Subset sum problem-backtracking

ALGORITHM :
STEP 1: Start the process.

STEP2:Declare the variables

STEP3:Read the number of elements.

STEP4:Using for loop read n number of values.

STEP 5: Start with an empty set.

STEP6:Add the next element from the list to the set.

STEP7:If the subset is having sum M, then stop with that subset as solution.

STEP8:If the subset is not feasible or if we have reached the end of the set, then back track through
the subset until we find the most suitable value.

STEP9:If the subset is feasible(sum of subset<M)then go to step7.

STEP10:If we have visited all the elements without finding a suitable subset and if no backtracking is
possible then stop without solution.

STEP11:Stop the process.


CODING :

#include<stdio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
int inc[50], w[50], sum, n;
void sumset(int i, int wt, int total);
int promising(int i, int wt, int total)
{
return ((wt + total >= sum) && (wt == sum || wt + w[i + 1] <= sum));
}

void main()
{
int i, j, temp, total = 0;
printf("\nEnter how many numbers:\n");
scanf("%d", &n);
printf("\nEnter %d numbers to the set:\n", n);
for(i = 0; i < n; i++)
{
scanf("%d", &w[i]);
total += w[i];
}

printf("\nInput the sum value to create subset:\n");


scanf("%d", &sum);
for(i = 0; i < n - 1; i++)
{
for(j = 0; j < n - i - 1; j++)
{
if(w[j] > w[j + 1]) {
temp = w[j];
w[j] = w[j + 1];
w[j + 1] = temp;
}
}
}

printf("\nThe given %d numbers in ascending order:\n", n);


for(i = 0; i < n; i++)
{
printf("%d\t", w[i]);
}

if(total < sum)


{
printf("\nSubset construction is not possible\n");
}
else
{
for(i = 0; i < n; i++)
{
inc[i] = 0; // Initialize inc array to 0
}
printf("\nThe solution using backtracking is:\n");
sumset(-1, 0, total);
}
}

void sumset(int i, int wt, int total)


{
int j;

if(promising(i, wt, total))


{
if(wt == sum)
{
printf("\n{\t");
for(j = 0; j <= i; j++)
{
if(inc[j])
{
printf("%d\t", w[j]);
}
}
printf("}\n");
}
else
{
inc[i + 1] = TRUE;
sumset(i + 1, wt + w[i + 1], total - w[i + 1]);
inc[i + 1] = FALSE;
sumset(i + 1, wt, total - w[i + 1]);
}
}
}
OUTPUT :

RESULT :

Thus the above Subset sum problem-back tracking program is successfully completed.
Ex.No: 12 IMPLEMENTATION OF TRAVELLING SALES PERSON PROBEM-BRANCH & BOUND
Date : 06.01.2025

AIM :
Write a C program to perform travelling sales person probem-branch & bound

ALGORITHM :
STEP1:Start the process.

STEP2:Declare and initialize the array[10][10], completed[10],n,cost=0.


STEP 3: Read the number of Villages.
STEP4:Read the cost matrix and do the following to find the minimum cost.

a. C(\{1\},1)=0.

b. for s=2to n do.

c. for all subsets Sin\1,2,3,...,n\of sizes and containing 1.

d. C(S,1)=∞.

e. for all j€S andine1.

f. C(S,j)=min\C(S-\{j\},i)+d(i,j)for i€S andinej.

g. Return min jC(\1,2,3,...,n\,j)+d(j,i).

STEP 5: Print the minimum cost spanning tree.

STEP 6: Stop the process.


CODING :

#include<stdio.h>
#define MAX 25
int matrix[MAX][MAX], visited_cities[MAX], limit, cost = 0;
int tsp(int c)
{
int count, nearest_city = -1;
int minimum = 999, temp;
for(count = 0; count < limit; count++)
{
if ((matrix[c][count] != 0) && (visited_cities[count] == 0))
{
if (matrix[c][count] < minimum)
{
minimum = matrix[c][count];
nearest_city = count;
temp = matrix[c][count];
}
}
}
if (nearest_city != -1)
{
cost += temp;
}
return nearest_city;
}

void minimum_cost(int city)


{
int nearest_city;
visited_cities[city] = 1;
printf("%d ", city + 1);
nearest_city = tsp(city);
if (nearest_city == -1)
{
nearest_city = 0;
printf("%d ", nearest_city + 1);
cost += matrix[city][nearest_city];
return;
}

minimum_cost(nearest_city);
}
int main()
{
int i, j;
printf("Enter total number of cities: ");
scanf("%d", &limit);
printf("\nEnter the cost matrix (use 0 for no path between cities):\n");
for(i = 0; i < limit; i++)
{
for(j = 0; j < limit; j++)
{
scanf("%d", &matrix[i][j]);
}
visited_cities[i] = 0;
}
printf("\nEntered cost matrix:\n");
for(i = 0; i < limit; i++)
{
for(j = 0; j < limit; j++)
{
printf("%d ", matrix[i][j]);
}
printf("\n");
}
printf("\nPath: ");
minimum_cost(0);
printf("\n\nMinimum cost: %d\n", cost);
return 0;
}
OUTPUT :

RESULT :
Thus the above travelling sales person probem-branch & bound program is successfully completed.

You might also like