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

DAA Lab Programs

Whole

Uploaded by

smdfaizan8147
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)
38 views

DAA Lab Programs

Whole

Uploaded by

smdfaizan8147
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/ 56

PART A

Ex.No.1 SELECTION SORT


AIM

Write a program to sort a list of N elements using Selection Sort Technique.

// C program for implementation of selection sort

#include <stdio.h>

void swap(int *xp, int *yp)

int temp = *xp;

*xp = *yp;

*yp = temp;

void selectionSort(int arr[], int n)

int i, j, min_idx;

// One by one move boundary of unsorted subarray

for (i = 0; i < n-1; i++)


{

// Find the minimum element in unsorted array

min_idx = i;

for (j = i+1; j < n; j++)

if (arr[j] < arr[min_idx])

min_idx = j;

// Swap the found minimum element with the first element

if(min_idx != i)

swap(&arr[min_idx], &arr[i]);

/* Function to print an array */

void printArray(int arr[], int size)

int i;

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

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

printf("\n");

// Driver program to test above functions

int main()
{

int arr[] = {64, 25, 12, 22, 11};

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

selectionSort(arr, n);

printf("Sorted array: \n");

printArray(arr, n);

return 0;

TRAVELLING SALESMAN PROBLEM


Ex.No.2

AIM

Write a program to perform Travelling Salesman Problem

ALGORITHM

The travelling salesman Algorithm states that - " From a given set of N cities and distance
between each pair of the cities, find the minimum path length in such a way that it covers each
and every city exactly once (without repletion of any path) and terminate the traversal at the
starting point or the starting city from where the traversal of the TSP Algorithm was initiated.

1) A cost variable and visited array will be used to keep track of the updated minimum cost and
whether a node is already visited or not

2)Start with a source vertex, mark it visited, find the next neighbor node with minimum cost.

3)If any of the neighbor nodes are unvisited, find the node with minimum distance and add it to
the cost variable.

4) Recur for the found next nodes till a next node is found with zero neighbors unvisited
PROGRAM

/* Travelling Salesman Problem*/

#include <stdio.h>
#include<limits.h>
int graph[10][10] = {
{12, 30, 33, 10, 45},
{56, 22, 9, 15, 18},
{29, 13, 8, 5, 12},
{33, 28, 16, 10, 3},
{1, 4, 30, 24, 20}
};
int visited[10], n, cost = 0;

/* creating a function to generate the shortest path */


void TSP(int node)

int i, next_node = INT_MAX;


int min = INT_MAX;

/* marking the vertices visited in an assigned array */


visited[node] = 1;

/* displaying the shortest path */


printf("%d --> ", node + 1);

/* checking the minimum cost edge in the graph */


for(i = 0; i < n; i++)
{
if((graph[node][i] != 0) && (visited[i] == 0))
{
if(graph[node][i] < min)
{
min = graph[node][i];
}
next_node = i;
}
}
if(min != INT_MAX)
{
cost = cost + min;
}
if(next_node == INT_MAX)
{
next_node = 0;
printf("%d", next_node + 1);
cost = cost + graph[node][next_node];
return;
}
TSP(next_node);
}

/* main function */
int main()
{
int i, j;
n = 5;
for(i = 0; i < n; i++)
{
visited[i] = 0;
}
printf("Shortest Path: ");
TSP(0);
printf("\nMinimum Cost: ");
printf("%d\n", cost);
return 0;
}

RESULT

Thus the given task is completed successfully.


EX.No. 3. 0/1 KNAPSACK PROBLEM

AIM
Write program to implement Dynamic Programming algorithm for the 0/1 Knapsack
problem.

ALGORITHM

Given N items where each item has some weight and profit associated with it and also given a
bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the
items into the bag such that the sum of profits associated with them is the maximum
possible.
The constraint here is we can either put an item completely into the bag or cannot put it at all
[It is not possible to put a part of an item into the bag].

PROGRAM

/* 0/1 Knapsack problem using Dynamic programming*/

#include <stdio.h>

int max(int a, int b)


{
return (a > b)? a : b;
}

// Returns the maximum value that can be put in a knapsack of capacity W


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];
}

int main()
{
int val[] = {60, 100, 120};
int wt[] = {10, 20, 30};
int W = 50;
int n = sizeof(val)/sizeof(val[0]);
printf("Knapsack problem using dynamic programming...\n");
printf("\nMaximum Profit or Value = %d", knapsack(W, wt, val, n));
return 0;
}

RESULT

Thus the given task is completed successfully.


EX.No. 4. FRACTIONAL KNAPSACK PROBLEM
AIM

Write a program to perform Knapsack Problem using Greedy Solution

ALGORITHM

Given the weights and profits of N items, in the form of {profit, weight} put these items in a
knapsack of capacity W to get the maximum total profit in the knapsack. In Fractional
Knapsack, we can break items for maximizing the total value of the knapsack.

1)Calculate the ratio (profit/weight) for each item.


2)Sort all the items in decreasing order of the ratio.
3)Do the following for every item i in the sorted order

Take the item with highest ratio and add them until we can't add the next item as whole

4) add the next item as much as we can (fraction)

PROGRAM

/*Knapsack problems using Greedy Algorithm*/

#include<stdio.h>
int main()
{

float profit[] = {60, 100, 120};


float weight[] = {10, 20, 30};
float capacity = 50;
float ratio[50],Totalvalue,temp,amount;
int i,j;
int n = sizeof(profit)/sizeof(profit[0]);

for(i=0;i<n;i++)
ratio[i]=profit[i]/weight[i];

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


for (j = i + 1; j < n; j++)
if (ratio[i] < ratio[j])
{
temp = ratio[j];
ratio[j] = ratio[i];
ratio[i] = temp;

temp = weight[j];
weight[j] = weight[i];
weight[i] = temp;

temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;
}

printf("Knapsack problems using Greedy Algorithm...\n");


for (i = 0; i < n; i++)
{
if (weight[i] > capacity)
break;
else
{
Totalvalue = Totalvalue + profit[i];
capacity = capacity - weight[i];
}
}
if (i < n)
Totalvalue = Totalvalue + (ratio[i]*capacity);
printf("\nThe maximum value is :%f\n",Totalvalue);
return 0;
}

RESULT
Thus the given task is completed successfully.
Ex. no. 5a Breadth First Traversal
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

/* Breadth First Traversal*/


// This struct represents a directed graph using
// adjacency list representation
typedef struct My_Graph {

// No. of vertices
int V;
bool adj[10][10];
} Graph;

Graph* Graph_create(int V)
{
Graph* G = malloc(sizeof(Graph));
G->V = V;

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


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

{
G->adj[i][j] = false;
}
}

return G;
}

// Function to add an edge to graph


void Graph_addEdge(Graph* G, int v, int w)
{
// Add w to v’s list.
G->adj[v][w] = true;
}

// Prints BFS traversal from a given source s


void Graph_BFS(Graph* G, int s)
{
// Mark all the vertices as not visited
bool visited[10];
for (int i = 0; i < G->V; i++) {
visited[i] = false;
}

// Create a queue for BFS


int queue[10];
int front = 0, rear = 0;

// Mark the current node as visited and enqueue it


visited[s] = true;
queue[rear++] = s;

while (front != rear)


{

// Dequeue a vertex from queue and print it


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

// Get all adjacent vertices of the dequeued


// vertex s.
// If an adjacent has not been visited,
// then mark it visited and enqueue it
for (int adjacent = 0; adjacent < G->V; adjacent++)
{
if (G->adj[s][adjacent] && !visited[adjacent])
{
visited[adjacent] = true;
queue[rear++] = adjacent;
}
}
}
}

// Driver code
int main()
{
// Create a graph
Graph* G = Graph_create(4);
Graph_addEdge(G, 0, 1);
Graph_addEdge(G, 0, 2);
Graph_addEdge(G, 1, 2);
Graph_addEdge(G, 2, 0);
Graph_addEdge(G, 2, 3);
Graph_addEdge(G, 3, 3);

printf("Following is Breadth First Traversal starting from vertex 0\n");


Graph_BFS(G, 2);

return 0;
}

Ex. no. 5b Depth First Traversal


// C code to implement above approach
#include <stdio.h>
#include <stdlib.h>

// Globally declared visited array


int vis[100];

// Graph structure to store number


// of vertices and edges and
// Adjacency matrix
struct Graph
{
int V;
int E;
int** Adj;
};

// Function to input data of graph


struct Graph* adjMatrix()
{
struct Graph* G = (struct Graph*) malloc(sizeof(struct Graph));
G->V = 7;
G->E = 7;
G->Adj = (int**)malloc((G->V) * sizeof(int*));
for (int k = 0; k < G->V; k++)
{
G->Adj[k] = (int*)malloc((G->V) * sizeof(int));
}

for (int u = 0; u < G->V; u++)


{
for (int v = 0; v < G->V; v++)
{
G->Adj[u][v] = 0;
}
}
G->Adj[0][1] = G->Adj[1][0] = 1;
G->Adj[0][2] = G->Adj[2][0] = 1;
G->Adj[1][3] = G->Adj[3][1] = 1;
G->Adj[1][4] = G->Adj[4][1] = 1;
G->Adj[1][5] = G->Adj[5][1] = 1;
G->Adj[1][6] = G->Adj[6][1] = 1;
G->Adj[6][2] = G->Adj[2][6] = 1;

return G;
}

// DFS function to print DFS traversal of graph


void DFS(struct Graph* G, int u)
{
vis[u] = 1;
printf("%d ", u);
for (int v = 0; v < G->V; v++)
{
if (!vis[v] && G->Adj[u][v])
{
DFS(G, v);
}
}
}

// Function for DFS traversal


void DFStraversal(struct Graph* G)
{
for (int i = 0; i < 100; i++) {
vis[i] = 0;
}
for (int i = 0; i < G->V; i++) {
if (!vis[i])
{
DFS(G, i);
}
}
}

// Driver code
void main()
{
struct Graph* G;
G = adjMatrix();
DFStraversal(G);
}

RESULT
Thus the given task is completed successfully.
EX. No. 7 QUIK SORT USING DIVIDE AND CONQUER

AIM
Write a test program to implement Divide and Conquer strategy. Eg : Quick sort
algorithm for sorting list of integer in ascending order.

ALGORITHM
Quicksort(A[l..r])
//Input: Subarray of array A[0..n −1], defined by its left and right
//Output: Subarray A[l..r] sorted in nondecreasing order
if l < r
s ←Partition(A[l..r]) //s is a split position
Quicksort(A[l..s−1])
Quicksort(A[s + 1..r])

Partition(A[l..r])
//Input: Subarray of array A[0..n − 1], defined by its left and right indices l and r (l < r)
//Output: Partition of A[l..r], with the split position returned as this function’s value
p ← A[l] i ← l;
j←r+1
repeat
repeat i ← i + 1 until A[i] ≥ p
repeat j ← j − 1 until A[j ] ≤ p
swap(A[i], A[j ])
until i ≥ j
swap(A[i], A[j ]) //undo last swap when i ≥ j
swap(A[l], A[j ])
return j

PROGRAM
/* Quik sort using divide and conquer*/
#include<stdio.h>

int partition(int A[],int low,int high)


{
int temp;
int pivot=A[high];
int i=low-1;
for(int j=low;j<=high;j++)
{
/*If current element is smaller than the pivot Increment index of smaller element*/
if(A[j]<pivot)
{
i++;
temp= A[i];
A[i]=A[j];
A[j]=temp;
}
}
temp = A[i+1];
A[i+1]=A[high];
A[high]=temp;
return (i+1);
}
void quickSort(int A[],int low,int high)
{
if(low<high)
{
int pi=partition(A,low,high);
quickSort(A,low,pi-1);
quickSort(A,pi+1,high);
}
}

int main()
{
int A[15],n,i;
printf("Enter the total number of elements\n");
scanf("%d",&n);

printf("Enter the elements one by one\n");


for(i=0;i<n;i++)
scanf("%d",&A[i]);

quickSort(A,0,n-1);
printf("Sorted Array\n");
for( i=0;i<n;i++)
printf("%d\n",A[i]);

return 0;
}

RESULT
Thus the given task is completed successfully.
EX. No. 8 MERGE SORT USING DIVIDE AND CONQUER

AIM
Write a program to implement merge sort algorithm for sorting list of integer in
ascending order.

ALGORITHM
Step 1: Start
Step 2: Declare an array and left, right, mid variable
Step 3: Perform merge function.
mergesort(array,left,right)
mergesort (array, left, right)
if left > right
return
mid= (left+right)/2
mergesort(array, left, mid)
mergesort(array, mid+1, right)
merge(array, left, mid, right)
Step 4: Stop

PROGRAM

// C program for Merge Sort


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

void merge(int A[], int l, int m, int r)


{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

// Create temp arrays


int L[n1], R[n2];

// Copy data to temp arrays L[] and R[]


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

// Merge the temp arrays back into A[l..r]


i = 0; // Initial index of first subarray

j = 0; // Initial index of second subarray

k = l; // Initial index of merged subarray

while (i < n1 && j < n2)


{
if (L[i] <= R[j])
{
A[k] = L[i];
i++;
}
else
{
A[k] = R[j];
j++;
}
k++;
}

// Copy the remaining elements of L[], if there are any


while (i < n1)
{
A[k] = L[i];
i++;
k++;
}

// Copy the remaining elements of R[], if there are any


while (j < n2)
{
A[k] = R[j];
j++;
k++;
}
}

// l is for left index and r is right index of the sub-array of array to be sorted
void mergeSort(int A[], int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for large l and r
int m = l + (r - l) / 2;

// Sort first and second halves


mergeSort(A, l, m);
mergeSort(A, m + 1, r);
merge(A, l, m, r);
}
}

int main()
{

int A[15],n,i;
printf("Enter the total number of elements\n");
scanf("%d",&n);
printf("Enter the elements one by one\n");
for(i=0;i<n;i++)
scanf("%d",&A[i]);

mergeSort(A, 0, n-1);

printf("Sorted Array\n");
for( i=0;i<n;i++)
printf("%d\n",A[i]);
getch();
return 0;

RESULT
Thus the given task is completed successfully.
EX. No. 9 MERGE SORT with n>5000

AIM
Sort a given set of n integer elements using Merge sort method and compute its time
complexity. Run the Program for varied values of n>5000, and record the time taken to sort.

ALGORITHM
Step 1: Start
Step 2: Declare an array and left, right, mid variable
Step 3: Perform merge function.
mergesort(array,left,right)
mergesort (array, left, right)
if left > right
return
mid= (left+right)/2
mergesort(array, left, mid)
mergesort(array, mid+1, right)
merge(array, left, mid, right)
Step 4: Stop

PROGRAM

// C program for Merge Sort


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

void merge(int A[], int l, int m, int r)


{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

// Create temp arrays


int L[n1], R[n2];
// Copy data to temp arrays L[] and R[]
for (i = 0; i < n1; i++)
L[i] = A[l + i];
for (j = 0; j < n2; j++)
R[j] = A[m + 1 + j];

// Merge the temp arrays back into A[l..r]


i = 0; // Initial index of first subarray

j = 0; // Initial index of second subarray

k = l; // Initial index of merged subarray

while (i < n1 && j < n2)


{
if (L[i] <= R[j])
{
A[k] = L[i];
i++;
}
else
{
A[k] = R[j];
j++;
}
k++;
}

// Copy the remaining elements of L[], if there are any


while (i < n1)
{
A[k] = L[i];
i++;
k++;
}

// Copy the remaining elements of R[], if there are any


while (j < n2)
{
A[k] = R[j];
j++;
k++;
}
}

// l is for left index and r is right index of the sub-array of array to be sorted

void mergeSort(int A[], int l, int r)


{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for large l and r
int m = l + (r - l) / 2;

// Sort first and second halves


mergeSort(A, l, m);
mergeSort(A, m + 1, r);
merge(A, l, m, r);
}
}

int main()
{

int A[6000],n,i;

// Use current time as seed for random generator


srand(time(0));
for (i = 0; i < 5001 ; i++)
{
int num = (rand() % (5000 - 10 + 1)) + 10;
A[i] =num;
}
mergeSort(A, 0, 5000);
printf("Sorted Array\n");
for( i=0;i<5001;i++)
printf("%d ",A[i]);
getch();
return 0;

RESULT
Thus the given task is completed successfully.
EX. No. 10 QUICK SORT with n>5000

AIM
Sort a given set of n integer elements using quick sort method and compute its time
complexity. Run the Program for varied values of n>5000, and record the time taken to sort.

ALGORITHM
Quicksort(A[l..r])
//Input: Subarray of array A[0..n −1], defined by its left and right
//Output: Subarray A[l..r] sorted in nondecreasing order
if l < r
s ←Partition(A[l..r]) //s is a split position
Quicksort(A[l..s−1])
Quicksort(A[s + 1..r])

Partition(A[l..r])
//Input: Subarray of array A[0..n − 1], defined by its left and right indices l and r (l < r)
//Output: Partition of A[l..r], with the split position returned as this function’s value
p ← A[l] i ← l;
j←r+1
repeat
repeat i ← i + 1 until A[i] ≥ p
repeat j ← j − 1 until A[j ] ≤ p
swap(A[i], A[j ])
until i ≥ j
swap(A[i], A[j ]) //undo last swap when i ≥ j
swap(A[l], A[j ])
return j

PROGRAM
/* Quik sort using divide and conquer*/
#include<stdio.h>
#include <stdlib.h>
#include<conio.h>
#include <time.h>

int partition(int A[],int low,int high)


{
int temp;
int pivot=A[high];
int i=low-1;

for(int j=low;j<=high;j++)
{
/*If current element is smaller than the pivot Increment index of smaller element*/
if(A[j]<pivot)
{
i++;
temp= A[i];
A[i]=A[j];
A[j]=temp;
}
}
temp = A[i+1];
A[i+1]=A[high];
A[high]=temp;
return (i+1);
}
void quickSort(int A[],int low,int high)
{
if(low<high)
{
int pi=partition(A,low,high);
quickSort(A,low,pi-1);
quickSort(A,pi+1,high);
}
}

int main()
{
int A[6000],n,i;

// Use current time as seed for random generator


srand(time(0));
for (i = 0; i < 5001 ; i++)
{
int num = (rand() % (5000 - 10 + 1)) + 10;
A[i] =num;
}

quickSort(A,0,5000);

printf("Sorted Array\n");
for( i=0;i<5001;i++)
printf("%d ",A[i]);
getch();
return 0;
}

RESULT
Thus the given task is completed successfully.
PART -B

Ex.No.1 ADJACENCY MATRIX OF A GRAPH

AIM

Write a C Program that accepts the vertices and edges for a graph and stores it as an
adjacency matrix.

ALGORITHM

Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph.


Let the 2D array be adj[][], a slot adj[i][j] = 1 indicates that there is an edge from vertex i to
vertex j.

Adjacency matrix for undirected graph is always symmetric. Adjacency Matrix is also
used to represent weighted graphs. If adj[i][j] = w, then there is an edge from vertex i to vertex j
with weight w.

//ALGORITHM Adjacency Matrix of a graph


Input Vertices
max_edges = n*(n-1)/2;
Initialize adj[i][j]=0 for all values
Input origin and destin of the edge
for i= 1 to max_edges do
if( origin>=n || destin>=n || origin<0 || destin<0 )
print "invalid vertex"
else
adj[destin][origin] = 1
loop
print adj[][]
Pros: Representation is easier to implement and follow. Removing an edge takes O(1) time.
Queries like whether there is an edge from vertex ‘u’ to vertex ‘v’ are efficient and can be done
O(1).

Cons: Consumes more space O(V^2). Even if the graph is sparse(contains less number of edges),
it consumes the same space. Adding a vertex is O(V^2) time.

PROGRAM

/*program to accept vertices and edges of a graph and prints its adjacency matrix*/
#include<stdio.h>
#include<conio.h>

int main()
{
int adj[10][10]; // adjacency matrix
int n;// number of vertices
int max_edges,origin,destin,i,j;

printf("Enter the number of vertices\n");


scanf("%d",&n);
max_edges = n*(n-1)/2;

for(i=0; i<=n-1; i++)


{
for(j=0; j<=n-1; j++)
adj[i][j]=0;
}
for(i=1; i<=max_edges; i++)
{
printf("\nEnter edge [ %d ] ( -1 -1 to quit ) : ",i);
scanf("%d %d",&origin,&destin);
if( (origin == -1) && (destin == -1) )
break;
if( origin>=n || destin>=n || origin<0 || destin<0 )
{
printf("\nInvalidvertex!\n");
i--;
}
else
{

adj[destin][origin] = 1;
}
}

printf("\nThe adjacency matrix is :: \n");


for(i=0; i<=n-1; i++)
{
for(j=0; j<=n-1; j++)
printf("%4d",adj[i][j]);
printf("\n");
}
getch();
return 0;
}

RESULT

Thus the given task is completed successfully.

OUTPUT

Enter the number of vertices


5

Enter edge [ 1 ] ( -1 -1 to quit ) : 0 1

Enter edge [ 2 ] ( -1 -1 to quit ) : 0 2

Enter edge [ 3 ] ( -1 -1 to quit ) : 0 3

Enter edge [ 4 ] ( -1 -1 to quit ) : 1 3

Enter edge [ 5 ] ( -1 -1 to quit ) : 2 3

Enter edge [ 6 ] ( -1 -1 to quit ) : 3 4

Enter edge [ 7 ] ( -1 -1 to quit ) : 4 2

Enter edge [ 8 ] ( -1 -1 to quit ) : -1 -1

The adjacency matrix is ::


0 0 0 0 0
1 0 0 0 0
1 0 0 0 1
1 1 1 0 0
0 0 0 1 0
Ex.No.2 IN-DEGREE and OUT-DEGREEOF A GRAPH

AIM

Implement function to print In-Degree, Out-Degree and to display that adjacency matrix.

ALGORITHM

Given a directed graph, the task is to count the in and out degree of each vertex of the
graph.
The total count of incoming edges to a particular vertex is known as the indegree of that
vertex, and the total number of outgoing edges from a particular vertex is known as the
outdegree of that vertex.

Step 1 : Input the graph edges


Step 2 : Form the adjacency matrix for that graph
step 3 : Calculate out_degree
For all nodes(vertexs)
sum += G[i][j]
end for
print the out-degree of the vertex

step 4 : Calculate in_degree


For all nodes(vertexs)
sum += G[j][i]
end for
print the in-degree of the vertex

PROGRAM

/*Implement function to print in - degree and out degree and to display that adjacency matrix.*/

#include<stdio.h>
#include<conio.h>
#define MAX 10
void accept_graph(int G[][MAX], int n)
{
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("Edge (V%d,V%d) exists? (Yes=1, No=0):",i,j);
scanf("%d",&G[i][j]);
}
}
}
void disp_adj_mat(int G[][MAX], int n)
{
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%4d",G[i][j]);
}
printf("\n");
}
}

void calc_out_degree(int G[][MAX], int n)


{
inti,j,sum;
for(i=0;i<n;i++)
{
sum=0;
for(j=0;j<n;j++)
{
sum += G[i][j];
}
printf("out-deg(V%d)=%d\n",i,sum);
}
}

void calc_in_degree(int G[][MAX], int n)


{
inti,j,sum;
for(i=0;i<n;i++)
{
sum=0;
for(j=0;j<n;j++)
{
sum += G[j][i];
}
printf("in-deg(V%d)=%d\n",i,sum);
}
}

void main()
{
int G[MAX][MAX],n;
printf("Enter no.ofvertices:");
scanf("%d",&n);
accept_graph(G,n);
printf("Adjacency Matrix:\n");
disp_adj_mat(G,n);
printf("Out degree:\n");
calc_out_degree(G,n);
printf("In degree:\n");
calc_in_degree(G,n);
}
RESULT

Thus the given task is completed successfully.

OUTPUT

Enter no.of vertices: 2

Edge (V0,V0) exists? (Yes=1, No=0):1

Edge (V0,V1) exists? (Yes=1, No=0):0

Edge (V1,V0) exists? (Yes=1, No=0):1

Edge (V1,V1) exists? (Yes=1, No=0):0

Adjacency Matrix:

10

10

Out degree:

out-deg(V0)=1

out-deg(V1)=1

In degree:

in-deg(V0)=2

in-deg(V1)=0
Ex.No.3 N QUEENS

AIM

Write program to implement backtracking algorithm for solving problems like N queens.

ALGORITHM

The N Queen is the problem of placing N chess queens on an N×N chessboard so that
no two queens attack each other.
For example, the following is a solution for the 4 Queen problem.
The idea is to place queens one by one in different columns, starting from the leftmost
column. When we place a queen in a column, we check for clashes with already placed queens.
In the current column, if we find a row for which there is no clash, we mark this row and
column as part of the solution. If we do not find such a row due to clashes, then we backtrack
and return false.

Step 1: Start in the leftmost column. If all queens are placed return true
Step 2: Try all rows in the current column. Do the following steps for every row.

Step 3: If the queen can be placed safely in this row


Then mark this [row, column] as part of the solution and recursively check if placing
queen here leads to a solution.

Step 4: If placing the queen in [row, column] leads to a solution then return true.

Step 5: If placing queen doesn’t lead to a solution then unmark this [row, column] then
backtrack and try other rows.

If all rows have been tried and valid solution is not found return false to trigger
backtracking.
PROGRAM

/* program to solve N Queen Problem using backtracking */


#define N 4
#include <stdbool.h>
#include <stdio.h>

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]. Note that this function is
called when "col" queens are already placed in columns from 0 to col -1. So we need to check only left
side for attacking queens */

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;

/* 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 Queen 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
}
}

/* If the queen cannot be placed in any row in


this column col then return false */
return false;
}

/* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil() to
solve the problem. It returns false if queens cannot be placed, otherwise, return true and
prints placement of queens in the form of 1s. Note that there may be more than one
solutions, this function prints one of the
feasible solutions.*/

bool solveNQ()
{
int board[N][N] = { { 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };

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

printSolution(board);
return true;
}

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

RESULT

Thus the given task is completed successfully.

OUTPUT
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0
Ex.No.4 SUM OF SUBSETS

AIM

Write a program to implement the backtracking algorithm for the sum of subsets
problem

ALGORITHM

Backtracking is a technique to solve dynamic programming problems. It works by going


step by step and rejects those paths that do not lead to a solution and trackback (moves back )
to the previous position.

PROBLEM STATEMENT

Given an array of integers and a sum, the task is to have all subsets of given array with
sum equal to the given sum.

In the subset sum problem, we have to find the subset of a set is such a way that the
element of this subset-sum up to a given number K. All the elements of the set are positive and
unique (no duplicate elements are present).

For this, we will create subsets and check if their sum is equal to the given number k

Subset sum can also be thought of as a special case of the 0–1 Knapsack problem. For each
item, there are two possibilities

case 1: Include the current element in the subset and recur for the remaining elements with the
remaining Sum.
case 2: Exclude the current element from the subset and recur for the remaining elements.

Finally, if Sum becomes 0 then print the elements of current subset. The recursion’s base case
would be when no items are left, or the sum becomes negative, then simply return.
Begin
if total = sum, then
display the subset
//go for finding next subset
subsetSum(set, subset, , subSize-1, total-set[node], node+1, sum)
return
else
for all element i in the set, do
subset[subSize] := set[i]
subSetSum(set, subset, n, subSize+1, total+set[i], i+1, sum)
done
End

PROGRAM

/*program to implement the backtracking algorithm for the sum of subsets problem */
#include <stdio.h>
#include <stdlib.h>

void printValues(int A[], int size)


{
for (int i = 0; i < size; i++)
{
printf("%*d", 5, A[i]);
}
printf("\n");
}

void subset_sum(int s[], int t[], int s_size, int t_size, int sum, int ite, int const target_sum)
{

if (target_sum == sum)
{
printValues(t, t_size);
subset_sum(s, t, s_size, t_size - 1, sum - s[ite], ite + 1, target_sum);
return;
}
else
{
for (int i = ite; i < s_size; i++)
{
t[t_size] = s[i];
subset_sum(s, t, s_size, t_size + 1, sum + s[i], i + 1, target_sum);
}
}
}

void generateSubsets(int s[], int size, int target_sum)


{
int* tuplet_vector = (int*)malloc(size * sizeof(int));
subset_sum(s, tuplet_vector, size, 0, 0, 0, target_sum);
free(tuplet_vector);
}

int main()
{
int set[] = { 1,2,3,4 };
int size = sizeof(set) / sizeof(set[0]);
printf("\n The set is :");
printValues(set , size);
printf("Given sum is : 7\n");
printf("\n The subsets are :\n");
generateSubsets(set, size, 7);
return 0;
}

RESULT

Thus the given task is completed successfully.

OUTPUT

The set is : 1 2 3 4
Given sum is : 7

The subsets are :


1 2 4
3 4
Ex.No.5 JOB SEQUENCING

AIM

Write program to implement greedy algorithm for job sequencing with deadlines.

ALGORITHM

Job scheduling algorithm is applied to schedule the jobs on a single processor to


maximize the profits.

The greedy approach of the job scheduling algorithm states that, “Given ‘n’ number of
jobs with a starting time and ending time, they need to be scheduled in such a way that
maximum profit is received within the maximum deadline”.

Set of jobs with deadlines and profits are taken as an input with the job scheduling
algorithm and scheduled subset of jobs with maximum profit are obtained as the final output.

Step1 : Find the maximum deadline value from the input set of jobs.
Step2 : Once, the deadline is decided, arrange the jobs in descending order of their
profits.
Step3 : Selects the jobs with highest profits, their time periods not exceeding the
maximum deadline.
Step4 : The selected set of jobs are the output.

PROGRAM

/*program to implement greedy algorithm for job sequencing with deadlines*/

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

// A structure to represent a job


typedef struct Job
{
char id; // Job Id
int dead; // Deadline of job
int profit; // Profit if job is over before or on
// deadline
} Job;

// This function is used for sorting all jobs according to profit


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

// Find minimum between two numbers.


int min(int num1, int num2)
{
return (num1 > num2) ? num2 : num1;
}

// Returns maximum profit from jobs


void printJobScheduling(Job arr[], int n)
{
// Sort all jobs according to decreasing order of profit
qsort(arr, n, sizeof(Job), compare);

int result[n]; // To store result (Sequence of jobs)


bool slot[n]; // To keep track of free time slots

// Initialize all slots to be free


for (int i = 0; i < n; i++)
slot[i] = false;

// 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 = min(n, arr[i].dead) - 1; j >= 0; j--)
{
// Free slot found
if (slot[j] == false)
{
result[j] = i; // Add this job to result
slot[j] = true; // Make this slot occupied
break;
}
}
}

// Print the result


for (int i = 0; i < n; i++)
if (slot[i])
printf("%c ", arr[result[i]].id);
}

// Driver's code
int main()
{
Job arr[] = { { 'a', 2, 100 },
{ 'b', 1, 19 },
{ 'c', 2, 27 },
{ 'd', 1, 25 },
{ 'e', 3, 15 } };
int n = sizeof(arr) / sizeof(arr[0]);
printf( "Following is maximum profit sequence of jobs \n");

// Function call
printJobScheduling(arr, n);
return 0;
}

RESULT

Thus the given task is completed successfully.

OUTPUT

Following is maximum profit sequence of jobs


cae

Ex.No.6 OPTIMAL BINARY SEARCH TREE


AIM

Write program to implement Dynamic Programming algorithm for the Optimal Binary
Search Tree Problem.

ALGORITHM
An Optimal Binary Search Tree is a variant of binary search trees where the arrangement of
nodes is strategically optimized to minimize the cost of searches. The key idea behind an OBST
is to place frequently accessed items closer to the root, reducing the search time for those
elements. Conversely, less frequently accessed items are placed further away, leading to a
balanced and efficient search tree

Begin
define cost matrix of size n x n
for i in range 0 to n-1, do
cost[i, i] := freq[i]
done

for length in range 2 to n, do


for i in range 0 to (n-length+1), do
j := i + length – 1
cost[i, j] := ∞
for r in range i to j, done
if r > i, then
c := cost[i, r-1]
else
c := 0
if r < j, then
c := c + cost[r+1, j]
c := c + sum of frequency from i to j
if c < cost[i, j], then
cost[i, j] := c
done
done
done
return cost[0, n-1]
End
PROGRAM

/* Program to find the minimum cost of a optimal binary search*/


#include<stdio.h>
#define INT_MAX 500
int sum(int freq[], int low, int high)
{ //sum of frequency from low to high range
int sum = 0;
for (int k = low; k <=high; k++)
sum += freq[k];
return sum;
}

int minCostBST(int keys[], int freq[], int n)


{
int cost[n][n];

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


cost[i][i] = freq[i];

for (int length=2; length<=n; length++)

{
for (int i=0; i<=n-length+1; i++)
{ //from 0th row to n-length+1 row as i
int j = i+length-1;
cost[i][j] = INT_MAX; //initially store to maximum value

for (int r=i; r<=j; r++)


{
//find cost when r is root of subtree
int c = ((r > i)?cost[i][r-1]:0)+((r < j)?cost[r+1][j]:0)+sum(freq, i, j);
if (c < cost[i][j])
cost[i][j] = c;
}
}
}
return cost[0][n-1];
}

int main() {
int keys[] = {10, 12, 20};
int freq[] = {34, 8, 50};
int n = 3;
printf("Cost of Optimal BST is: %d ", minCostBST(keys, freq, n));
}

RESULT

Thus the given task is completed successfully.

OUTPUT

Cost of Optimal BST is: 142

Ex.No.7 PRIM’s ALGORITHM

AIM
Write a program that implements Prim's algorithm to generate minimum cost spanning
Tree.
ALGORITHM

A spanning tree is a sub-graph of an undirected connected graph, which includes all


the vertices of the graph with a minimum possible number of edges.

A minimum spanning tree (MST) is a subset of the edges of a connected, edge-weighted


graph that connects all the vertices together without any cycles and with the minimum
possible total edge weight

The steps for implementing Prim's algorithm are as follows:

Step 1: Initialize the minimum spanning tree with a vertex chosen at random.
Step 2: Find all the edges that connect the tree to new vertices, find the minimum and add it to
the tree
Step 3: Keep repeating step 2 until we get a minimum spanning tree

PROGRAM

#include <stdio.h>
#include <limits.h>
#define vertices 5 /*Define the number of vertices in the graph*/
/* create minimum_key() method for finding the vertex that has minimum key-value and that is
not added in MST yet */
int minimum_key(int k[], int mst[])
{
int minimum = INT_MAX, min,i;

/*iterate over all vertices to find the vertex with minimum key-value*/
for (i = 0; i < vertices; i++)
if (mst[i] == 0 && k[i] < minimum )
minimum = k[i], min = i;
return min;
}
/* create prim() method for constructing and printing the MST.
The g[vertices][vertices] is an adjacency matrix that defines the graph for MST.*/
void prim(int g[vertices][vertices])
{
/* create array of size equal to total number of vertices for storing the MST*/
int parent[vertices];
/* create k[vertices] array for selecting an edge having minimum weight*/
int k[vertices];
int mst[vertices];
int i, count,edge,v; /*Here 'v' is the vertex*/
for (i = 0; i < vertices; i++)
{
k[i] = INT_MAX;
mst[i] = 0;
}
k[0] = 0; /*It select as first vertex*/
parent[0] = -1; /* set first value of parent[] array to -1 to make it root of MST*/
for (count = 0; count < vertices-1; count++)
{
/*select the vertex having minimum key and that is not added in the MST yet from the set
of vertices*/
edge = minimum_key(k, mst);
mst[edge] = 1;
for (v = 0; v < vertices; v++)
{
if (g[edge][v] && mst[v] == 0 && g[edge][v] < k[v])
{
parent[v] = edge, k[v] = g[edge][v];
}
}
}
/*Print the constructed Minimum spanning tree*/
printf("\n Edge \t Weight\n");
for (i = 1; i < vertices; i++)
printf(" %d <-> %d %d \n", parent[i], i, g[i][parent[i]]);

}
int main()
{
int g[vertices][vertices] = {{0, 0, 3, 0, 0},
{0, 0, 10, 4, 0},
{3, 10, 0, 2, 6},
{0, 4, 2, 0, 1},
{0, 0, 6, 1, 0},
};
prim(g);
return 0;
}
RESULT

Thus the given task is completed successfully.

OUTPUT

Edge Weight
3 <-> 1 4
0 <-> 2 3
2 <-> 3 2
3 <-> 4 1

--------------------------------
Process exited after 1.827 seconds with return value 0
Press any key to continue . . .

Ex.No.8 KRUSKAL’S ALGORITHM

AIM

Write a program that implements Kruskal's algorithm to generate minimum cost


spanning tree.

ALGORITHM
A spanning tree is a sub-graph of an undirected connected graph, which includes all
the vertices of the graph with a minimum possible number of edges.

A minimum spanning tree (MST) is a subset of the edges of a connected, edge-


weighted graph that connects all the vertices together without any cycles and with the
minimum possible total edge weight.

Step 1 : Sort all the edges in non-decreasing order of their weight.


Step 2 : Pick the smallest edge. Check if it forms a cycle with the spanning tree
formed so far. If the cycle is not formed, include this edge. Else, discard it.
Step 3 : Repeat step#2 until there are (V-1) edges in the spanning tree.

PROGRAM

/* Program to implement Krushkal Algorithm*/


#include <stdio.h>

#define MAX 30

typedef struct edge


{
int u, v, w;
} edge;

typedef struct edge_list


{
edge data[MAX];
int n;
} edge_list;

edge_list elist;

int Graph[MAX][MAX], n;
edge_list spanlist;

void kruskalAlgo();
int find(int belongs[], int vertexno);
void applyUnion(int belongs[], int c1, int c2);
void sort();
void print();
// Applying Krushkal Algo
void kruskalAlgo()
{
int belongs[MAX], i, j, cno1, cno2;
elist.n = 0;

for (i = 1; i < n; i++)


for (j = 0; j < i; j++)

{
if (Graph[i][j] != 0)
{
elist.data[elist.n].u = i;
elist.data[elist.n].v = j;
elist.data[elist.n].w = Graph[i][j];
elist.n++;
}
}

sort();

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


belongs[i] = i;

spanlist.n = 0;

for (i = 0; i < elist.n; i++)


{
cno1 = find(belongs, elist.data[i].u);
cno2 = find(belongs, elist.data[i].v);

if (cno1 != cno2)
{
spanlist.data[spanlist.n] = elist.data[i];
spanlist.n = spanlist.n + 1;
applyUnion(belongs, cno1, cno2);
}
}
}

int find(int belongs[], int vertexno)


{
return (belongs[vertexno]);
}
void applyUnion(int belongs[], int c1, int c2)
{
int i;

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


if (belongs[i] == c2)
belongs[i] = c1;
}

// Sorting algo
void sort()
{
int i, j;
edge temp;

for (i = 1; i < elist.n; i++)


for (j = 0; j < elist.n - 1; j++)
if (elist.data[j].w > elist.data[j + 1].w)
{
temp = elist.data[j];
elist.data[j] = elist.data[j + 1];
elist.data[j + 1] = temp;
}
}

// Printing the result


void print()
{
int i, cost = 0;

for (i = 0; i < spanlist.n; i++)


{
printf("\n%d - %d : %d", spanlist.data[i].u, spanlist.data[i].v, spanlist.data[i].w);
cost = cost + spanlist.data[i].w;
}

printf("\nSpanning tree cost: %d", cost);


}

int main()
{
int i, j, total_cost;
n = 6;

Graph[0][0] = 0;
Graph[0][1] = 4;
Graph[0][2] = 4;
Graph[0][3] = 0;
Graph[0][4] = 0;
Graph[0][5] = 0;
Graph[0][6] = 0;

Graph[1][0] = 4;
Graph[1][1] = 0;
Graph[1][2] = 2;
Graph[1][3] = 0;
Graph[1][4] = 0;
Graph[1][5] = 0;
Graph[1][6] = 0;

Graph[2][0] = 4;
Graph[2][1] = 2;
Graph[2][2] = 0;
Graph[2][3] = 3;
Graph[2][4] = 4;
Graph[2][5] = 0;
Graph[2][6] = 0;

Graph[3][0] = 0;
Graph[3][1] = 0;
Graph[3][2] = 3;
Graph[3][3] = 0;
Graph[3][4] = 3;
Graph[3][5] = 0;
Graph[3][6] = 0;

Graph[4][0] = 0;
Graph[4][1] = 0;
Graph[4][2] = 4;
Graph[4][3] = 3;
Graph[4][4] = 0;
Graph[4][5] = 0;
Graph[4][6] = 0;

Graph[5][0] = 0;
Graph[5][1] = 0;
Graph[5][2] = 2;
Graph[5][3] = 0;
Graph[5][4] = 3;
Graph[5][5] = 0;
Graph[5][6] = 0;

kruskalAlgo();
print();
}

RESULT

Thus the given task is completed successfully.

OUTPUT

2-1:2
5-2:2
3-2:3
4-3:3
1-0:4
Spanning tree cost: 14
--------------------------------
Process exited after 1.867 seconds with return value 0
Press any key to continue . . .

You might also like