77
Lab Manual: Algorithms Laboratory CONTENT SHEET SLNO . EXPERIMENT NAME PAGE NO. 1. Implement Recursive Binary search and Linear search and determine the time required to search an element. Repeat the experiment for different values of n, the number of elements in the list to be searched and plot a graph of the time taken versus n. 2. Sort a given set of elements using the Heap sort method and determine the time required to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the taken versus n. 3. Sort a given set of elements using Merge sort method and determine the time required to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n. 4. Sort a given set of elements using Selection sort and determine the time required to sort elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n. 5. a) Obtain the Topological ordering of vertices in a given digraph. b) Print all the nodes reachable from a given starting node in a digraph using DFS method. 6. Implement 0/1 Knapsack problem using dynamic programming. 1

Adalab Manual

Embed Size (px)

Citation preview

Page 1: Adalab Manual

Lab Manual: Algorithms Laboratory

CONTENT SHEET

SLNO. EXPERIMENT NAME PAGE NO.

1. Implement Recursive Binary search and Linear search and determine the time required to search an element. Repeat the experiment for different values of n, the number of elements in the list to be searched and plot a graph of the time taken versus n.

2. Sort a given set of elements using the Heap sort method and determine the time required to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the taken versus n.

3. Sort a given set of elements using Merge sort method and determine the time required to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n.

4. Sort a given set of elements using Selection sort and determine the time required to sort elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n.

5. a) Obtain the Topological ordering of vertices in a given digraph.

b) Print all the nodes reachable from a given starting node in a digraph using DFS method.

6. Implement 0/1 Knapsack problem using dynamic programming.

7. From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstra’s algorithm.

8. Sort a given set of elements using Quick sort method and determine the time required sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n.

9. Find Minimum Cost Spanning Tree of given undirected graph using Kruskal’s algorithm.

10. a) Print all the nodes reachable from a given starting node in a digraph using BFS method.b) Check whether a given graph is connected of not using DFS method.

1

Page 2: Adalab Manual

Lab Manual: Algorithms Laboratory

11. Find a subset of a given set S = {s1,s2,……………,sn} of n positive integers whose sum is equal to a given positive integer d. For example, if S = {1,2,5,6,8} and d=9 there are two solutions {1,2,6} and {1,8}. A suitable message is to be displayed if the given problem instance doesn’t have a problem.

12. a) Implement Horspool algorithm for String Matching. b) Find the Binomial Co-efficient using Dynamic Programming.

13. Find Minimum Cost Spanning Tree of given undirected graph using Prim’s algorithm.

14. a) Implement Floyd’s algorithm for the All-Pairs-Shortest-Paths problem.

b) Compute the transitive closure of a given directed graph using Warshall’s algorithm.

15. Implement N Queen’s problem using Back Tracking.

2

Page 3: Adalab Manual

Lab Manual: Algorithms Laboratory

I. Implement Recursive Binary search and Linear search and determine the time required to search an element. Repeat the experiment for different values of n, the number of elements in the list to be searched and plot a graph of the time taken versus n.

►Linear Search:

Design Strategy: Brute-Force ALGORITHM LinearSearch(A[0..n],K) //The algorithm implements sequential search with a // search key as a sentinel //Input: An array A of n elements and a search key K //Output: The position of the first element in A[0..n-1] // whose value is equal to K or -1 of no such // element is found A[n]←K i ← 0 while A[ i ] ≠ K do i← i+1 if i <n return i else return -1

►Binary Search:

Design Strategy: Divide-and-Conquer

ALGORITHM BinarySearch(A[l…r],K)

//Implements recursive binary search //Input: An array A[l..r] sorted in non decreasing // order & a search key K //Output: An index of the array’s element that is equal // to K or -1 if there is no such element if l > r return -1 else mid ← └(l+r)/2┘ if A[mid] = K return mid else if K < A[mid] return BinarySearch(A[l… mid-1],K) else return BinarySearch(A[mid+1… r],K)

3

Page 4: Adalab Manual

Lab Manual: Algorithms Laboratory

/* RECURSIVE LINEAR & BINARY SEARCH */#include<stdio.h>#include<conio.h>#include<time.h>#include<process.h>

int key;

int linear(int a[],int n){

if(n==-1)return -1;

else if(key==a[n])return n;

elsereturn linear(a,n-1);

}

int binary(int a[],int low,int high){

int mid;mid=(low+high)/2;if(low>high)

return -1;else if(key==a[mid])

return mid;else if(key<a[mid])

return binary(a,low,mid-1);else

return binary(a,mid+1,high);}

void main(){

int a[10],pos,n,c,i;clock_t start,end;clrscr();printf("\n Enter the no of elements : ");scanf("%d",&n);printf("\n Enter the Array elements : ");for(i=0;i<n;i++)

scanf("%d",&a[i]);printf("\n Enter the key : ");scanf("%d",&key);printf("\n Enter Choice: 1.Linear 2.Binary : ");

4

Page 5: Adalab Manual

Lab Manual: Algorithms Laboratory

scanf("%d",&c);if(c==1){

start=clock();pos=linear(a,n-1);end=clock();

}else if(c==2){

start=clock();pos=binary(a,0,n-1);end=clock();

}else{

printf("\n Wrong Choice \n");getch();exit(0);

}if(pos==-1){

printf("\n Unsuccessful Search \n");printf("\n\n The Time is %f \n\n",(end-start)/CLK_TCK);

}else{

printf("\n Key found successfully at %d position",pos+1);printf("\n\n The Time is %f \n\n",(end-start)/CLK_TCK);

}getch();

}

/**************************** OUTPUT ******************** Enter the no of elements : 5 Enter the Array elements : 12 5 6 4 10

Enter the key : 4

Enter Choice: 1.Linear 2.Binary : 1

Key found successfully at 4 position

The Time is 0.000000

5

Page 6: Adalab Manual

Lab Manual: Algorithms Laboratory

Enter the no of elements : 5

Enter the Array elements : 12 5 6 4 10

Enter the key : 15

Enter Choice: 1.Linear 2.Binary : 1

Unsuccessful Search

The Time is 0.000000

Enter the no of elements : 5 Enter the Array elements : 11 22 33 44 55 Enter the key : 55 Enter Choice: 1.Linear 2.Binary : 2 Key found successfully at 5 position The Time is 0.000000

Enter the no of elements : 5 Enter the Array elements : 11 22 33 44 55 Enter the key : 66 Enter Choice: 1.Linear 2.Binary : 2 Unsuccessful Search

The Time is 0.000000

*******************************************************/

6

Page 7: Adalab Manual

Lab Manual: Algorithms Laboratory

II. Sort a given set of elements using the Heapsort method and determine the time required to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the taken versus n.

ALGORITHM heap sort Stage 1: (Heap construction): construct a heap for a given array.Stage 2: (maximum deletions): apply the root-deletion operation n-1 times to the remaining heapDeleting root’s key with the last key k of the heap can be done by the following algorithm.

Step 1: exchange the root’s key with the last key k of the heap.Step 2: Decrease the heap’s size.Step 3: “Heapify the smaller tree by shifting k down the tree exactly in the same way we did it in the bottom-up heap construction algorithm .That is, verify the parental dominance for k : if it holds ,we are done ; if not, swap k with the larger of its children and repeat this operation until the parental dominance condition holds for k in its new position.

Design strategy: Transform and Conquer

ALGORITHM HeapbottomUp (H [1...n]// constructs a heap from the elements of a given array//by the bottom-up algorithm//Input: An array H [1...n] of orderable items//Output: A heap H[1…n]

for i←|_n/2_| down to 1 dok←i; v← H[k] heap←false

While not heap and 2* k<=n doJ←2*kif j<n //there are two children

if H[j]<H[j+1] j←j+1if v>=H[j]

heap←true else H[k]←H[j]: k←j

H[k]←v

7

Page 8: Adalab Manual

Lab Manual: Algorithms Laboratory

/* HEAP SORT */#include<stdio.h>#include<conio.h>#include<process.h>#include<time.h>clock_t start,end;

void heap(int a[],int n){

int c,p,k,item;for(k=1;k<n;k++){

item=a[k];c=k;p=(c-1)/2;while(c>0 && item >a[p]){

a[c]=a[p];c=p;p=(c-1)/2;

}a[c]=item;

}}

void heapf(int a[],int n){

int c,p,item;p=0;item=a[p];c=(2*p)+1;while(c<=n-1){

if(c+1 <= n-1)if(a[c] < a[c+1])

c++;if(item < a[c]){

a[p] = a[c];p = c;c = (2*p)+1;

}else break;

}a[p] = item;

}

8

Page 9: Adalab Manual

Lab Manual: Algorithms Laboratory

void heap_sort(int a[],int n){

int i,t;heap(a,n);for(i=n-1;i>0;i--){

t=a[0];a[0]=a[i];a[i]=t;heapf(a,i);

}}

void main(){

int a[20],n,i;clrscr();printf("Enter the number of elements : ");scanf("%d",&n);printf("\nEnter the array elements : ");for(i=0;i<n;i++)

scanf("%d",&a[i]);start=clock();heap_sort(a,n);end=clock();printf("\n The sorted array : ");for(i=0;i<n;i++)

printf("%d \t",a[i]);printf("\n\n Time taken is : %f\n",(start-end)/CLK_TCK);getch();

}

/********************** OUTPUT ********************Enter the number of elements : 5 Enter the array elements : 10 98 56 54 67 The sorted array : 10 54 56 67 98 Time taken is : 0.000000

**************************************************/

9

Page 10: Adalab Manual

Lab Manual: Algorithms Laboratory

III. Sort a given set of elements using Merge sort method and determine the time required to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n.

ALGORITHM Merge (B [0...p-1], C [0...q-1], A [0...p+q-1])// Merges two sorted arrays into one sorted array// Input: arrays B [0...p-1] and C [0...q-1] both sorted// Output: sorted array A [0...p+q-1] of the elements of B and C i← 0 ; j←0 ; k←0 while i < p and j < q do if B[i] <= C[j] A [k] ← B [i]; i←i+1 else A [k]←C [j]; j←j+1 k←k+1 if i = p Copy C [j...q-1] to A [k...p+q-1]else copy B [i...p-1] to A [k...p+q-1]

Design Strategy: Divide and Conquer

ALGORITHM Mergesort (A [0..n-1] )// Sorts array (A [0..n-1]) by recursive Mergesort//Input: An array (A [0..n-1] of orderable elements//Output: Array (A [0..n-1]) sorted in non decreasing orderif n>1 copy A[0..|_n/2_| - 1] to B[0..|_n/2_| -1] copy A [|_n/2_|... n-1] to C[0...|--n/2--|-1] Mergesort (B [0...|_n/2_|-1]) Mergesort(C [0...|--n/2--|-1]) Merge (B, C, A)

10

Page 11: Adalab Manual

Lab Manual: Algorithms Laboratory

/* MERGE SORT */#include<stdio.h>#include<conio.h>#include<time.h>#include<process.h>int n,a[10];void sim_merge(int,int,int);void merge(int,int);

void main(){

int i;clock_t start,end;clrscr();printf("\n Enter the no. of elements in the vector: ");scanf("%d",&n);printf("\n Enter the Vector elements : ");for(i=0;i<n;i++)

scanf("%d",&a[i]);start=clock();merge(0,n-1);end=clock();printf("\n Sorted Vector as follows : ");for(i=0;i<n;i++)

printf(" %d ",a[i]);printf("\n\n The time taken is %f \n",(end-start)/(CLK_TCK));getch();

}

void sim_merge(int low,int mid,int high){

int c[10],i=low,j=mid+1,k=low;while(i<=mid && j<=high){

if(a[i]<a[j])c[k++]=a[i++];

elsec[k++]=a[j++];

}while(i<=mid)

c[k++]=a[i++];while(j<=high)

c[k++]=a[j++];for(i=low;i<=high;i++)

a[i]=c[i];}

11

Page 12: Adalab Manual

Lab Manual: Algorithms Laboratory

void merge(int low,int high){

int mid;if(low<high){

mid=(low+high)/2;merge(low,mid);merge(mid+1,high);sim_merge(low,mid,high);

}}

/************************** OUTPUT **********************

Enter the no. of elements in the vector: 5 Enter the Vector elements : 0 33 77 22 11 Sorted Vector as follows : 0 11 22 33 77 The time taken is 0.000000

*****************************************************/

12

Page 13: Adalab Manual

Lab Manual: Algorithms Laboratory

IV. Sort a given set of elements using Selection sort and determine the time required to sort elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n.

Design Strategy: Brute Force

ALGORITHM SelectionSort(A[0..n-1]) //The algorithm sorts a given array by selection sort //Input: An array A[0..n-1] of orderable elements //Output: array A[0..n-1] sorted in ascending order for i ← 0 to n-2 do min ← i for j ←i+1 to n-1 do if A[ j ]<A[min] min ← j swap A[ i ] and A[min]

13

Page 14: Adalab Manual

Lab Manual: Algorithms Laboratory

/* SELECTION SORT */#include<stdio.h>#include<conio.h>#include<process.h>#include<time.h>clock_t start,end;void main(){

int a[10],n,i,j,pos=0,t,s;clrscr();printf("\n Enter the number of elements : ");scanf("%d",&n);printf("\n Enter the array elements : ");for(i=0;i<n;i++)

scanf("%d",&a[i]);start=clock();for(i=0;i<n-1;i++){

s = a[i];for(j=i+1;j<n;j++)

if(s > a[j]){

s = a[j];pos = j;

}t = a[i];a[i] = a[pos];a[pos] = t;

}end=clock();printf("\n The sorted array is : ");for(i=0;i<n;i++)

printf("%d \t",a[i]);printf("\n\n The Time taken is : %f\n",(start-end)/CLK_TCK);getch();

}

/***************************** OUTPUT ************************** Enter the number of elements : 5

Enter the array elements : 76 45 87 34 09

The sorted array is : 9 34 45 76 87

The Time taken is : 0.000000***************************************************************/

14

Page 15: Adalab Manual

Lab Manual: Algorithms Laboratory

V. a) Obtain the Topological ordering of vertices in a given digraph.

b) Print all the nodes reachable from a given starting node in a digraph using DFS method.

a) Obtain the Topological ordering of vertices in a given digraph.

Design strategy : Decrease and Conquer (Application of DFS)

ALGORITHM topological sorting (G<V,E>)// Input: A directed acyclic graph G<V,E>//Output: a topologically sorted list

Step 1 : Perform a DFS traversal and note the order in which the vertices become dead ends(i.e, are popped off the traversal stack).

Step 2: Reversing this order yields a solution to the topological sorting.

Second method:

Design Strategy: Decrease and conquer.

Solution

ALGORITHM:

Step 1: Repeatedly, identify in a remaining diagraph a source which is a vertex with no incoming edges ,and delete it along with all the edges outgoing from it.(if they are several source ,break the tie arbitrarily).Step 2: The order in which the vertices are deleted yields a solution to Topological sorting problem.

INPUT: A directed acyclic graph

OUTPUT: the topological sorting of above directed acyclic graph is 2 1 3 4 5

1

3

2 5

4

15

Page 16: Adalab Manual

Lab Manual: Algorithms Laboratory

/* TOPOLOGICAL SORTING */

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

int a[10][10],vis[10],exp[10],n,j;void dfs(int);

void main(){

int i,m,x,y;clrscr();printf("\n Enter the no. of vertices : ");scanf("%d",&n);

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

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

a[i][j]=0;}vis[i]=0;

}printf("\n Enter the no. of edges : ");scanf("%d",&m);for(i=1;i<=m;i++){

printf("\n Enter the edge : ");scanf("%d %d",&x,&y);a[x][y]=1;

}j=0;for(i=1;i<=n;i++){

if(vis[i]==0)dfs(i);

}

printf("\n\n Topological order is : ");for(i=n-1;i>=0;i--)

printf(" %d ",exp[i]);getch();

}

16

Page 17: Adalab Manual

Lab Manual: Algorithms Laboratory

void dfs(int v){

int i;vis[v]=1;for(i=1;i<=n;i++){

if(a[v][i] == 1 && vis[i] == 0)dfs(i);

}exp[j++]=v;

}/**************************** OUTPUT ************************* Enter the no. of vertices : 7 Enter the no. of edges : 6 Enter the edge : 1 2 Enter the edge : 2 3 Enter the edge : 3 4 Enter the edge : 4 5 Enter the edge : 5 6 Enter the edge : 6 7 Topological order is : 1 2 3 4 5 6 7 Enter the no. of vertices : 5 Enter the no. of edges : 5 Enter the edge : 1 3 Enter the edge : 2 3 Enter the edge : 3 5 Enter the edge : 4 5 Enter the edge : 3 4

Topological order is : 2 1 3 4 5 **************************************************************/

17

Page 18: Adalab Manual

Lab Manual: Algorithms Laboratory

b) Print all the nodes reachable from a given starting node in a digraph using DFS method.

Design Strategy: Decrease and conquer.

ALGORITHM DFS(G)

//Implements a depth-first search traversal of a given graph

//Input: Graph G=<V, E>

//Output: Graph G with its vertices marked with consecutive integers in the order they //have been first encountered by the DFS traversal

mark each vertex in V with 0 as a mark of being “unvisited”Count←0for each vertex v in V do

if v is marked with 0dfs (v)

dfs(v)

//visits recursively all the unvisited vertices connected to vertex v and assigns them the

//numbers in the order they are encountered via global variable countcount←count+1 ; mark v with countfor each vertex w in V adjacent to v do

if w is marked with 0dfs(w)

18

Page 19: Adalab Manual

Lab Manual: Algorithms Laboratory

/* DFS PROGRAM */#include<stdio.h>#include<conio.h>

int a[10][10],vis[10],n;void dfs(int);

void main(){

int i,j,source;clrscr();printf("\n Enter the no. of vertices : ");scanf("%d",&n);printf("\n Enter the adjacency matrix : \n");for(i=1;i<=n;i++){

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

scanf("%d",&a[i][j]);}

}printf("\n Enter the source vertex : ");scanf("%d",&source);printf("\n Nodes reachable from %d vertex is : ",source);dfs(source);getch();

}

void dfs(int v){

int i;vis[v]=1;printf(" %d ",v);for(i=1;i<=n;i++){

if(a[v][i]==1 && vis[i]==0)dfs(i);

}}

19

Page 20: Adalab Manual

Lab Manual: Algorithms Laboratory

/*************************** OUTPUT ****************************

Enter the no. of vertices : 4 Enter the adjacency matrix : 0 1 0 1 0 0 1 0 0 0 0 0 0 0 1 0 Enter the source vertex : 1 Nodes reachable from 1 vertex is : 1 2 3 4

Enter the no. of vertices : 4 Enter the adjacency matrix : 0 1 1 0 1 0 0 1 1 0 0 0 0 1 0 0 Enter the source vertex : 2 Nodes reachable from 2 vertex is : 2 1 3 4

***************************************************************/

20

Page 21: Adalab Manual

Lab Manual: Algorithms Laboratory

VI. Implement 0/1 Knapsack problem using dynamic programming.

Design strategy: Dynamic programming.

ALGORITHM MFKnapsack(i,j)

// Implement the memory function method for the knapsack problem// Input: A nonnegative integer i indicating the number of the first items being considered // and a nonnegative integer j indicating the knapsack capacity.

// Output: the value of an optimal feasible subset of the first i items//note: uses as global variable input arrays weights [1…n], values [1…n] and table v[0…n,0…w] whose entries are initialized with -1 except for row 0 and column 0 initialized with 0’s

if v[i,j] <0 if j<weights[i] value←MFKnapsack(i-1,j) else value←max(MFKnapsack(i-1,j),values[i]+MFKnapsack(i-1,j-weights[i]))

v [i,j]←value

return v[i,j]

INPUT: Enter the number of objects, Knapsack capacity, weights and profits of each object.item weights Value

1 1 20

2 2 60

3 3 20

4 1 30

OUTPUT:

W1=1, v1=20

W2=2,v2=60

W3=3,v3=20

W4=1, v4=30

The maximum profit is 110 and the solution vector is 1 2 4.

i 0 1 2 3 4 5

0 0 0 0 0 0 0

1 0 20 20 20 20 20

2 0 20 60 80 80 80

3 0 20 60 80 80 80

4 0 30 60 90 110 110

21

Page 22: Adalab Manual

Lab Manual: Algorithms Laboratory

/* KNAPSACK PROGRAM */#include<stdio.h>#include<conio.h>

int knapsack(int,int);void objects(int,int);int max(int,int);int w[10],p[10],v[10][10],x[10],i,j;

void main(){

int n,m,y;clrscr();printf("\n\n Enter the no. of objects available : ");scanf("%d",&n);printf("\n\n Enter the capacity of the knapsack : ");scanf("%d",&m);printf("\n\n Enter the weights n profits of all objects : \n");for(i=1;i<=n;i++){

scanf("%d %d",&w[i],&p[i]);x[i]=0;

}y=knapsack(n,m);printf("\n\n Optimum Profit is : %d \n",y);objects(n,m);getch();

}int knapsack(int n,int m){

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

printf("\n");for(j=0;j<=m;j++){

if(i==0 || j==0)v[i][j]=0;

else if(w[i]>j)v[i][j]=v[i-1][j];

elsev[i][j]=max(v[i-1][j],(v[i-1][j-w[i]]+p[i]));

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

}return v[n][m];

}

22

Page 23: Adalab Manual

Lab Manual: Algorithms Laboratory

void objects(int n,int m){

i=n;j=m;while(i!=0 && j!=0){

if(v[i][j] != v[i-1][j]){

x[i]=1;j=j-w[i];

}i--;

}printf("\n\n Objects selected are : ");for(i=0;i<=n;i++){

if(x[i] == 1)printf(" %d ",i);

}}

int max(int a,int b){

if(a<b)return b;

elsereturn a;

}

/*************************** OUTPUT ************************ Enter the no. of objects available : 4 Enter the capacity of the knapsack : 5 Enter the weights n profits of all objects :1 202 603 201 30

0 0 0 0 0 00 20 20 20 20 200 20 60 80 80 800 20 60 80 80 800 30 60 90 110 110

Optimum Profit is : 110 Objects selected are : 1 2 4

************************************************************/

23

Page 24: Adalab Manual

Lab Manual: Algorithms Laboratory

VII. From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstra’s algorithm.

Design strategy: Greedy Method

ALGORITHM dijkstra’s (G, s)//dijkstra’s algorithm for single-source shortest paths.

//Input: A weighted connected graph G= (V, E) and its vertex s

// Output: The length dv of a shortest path from s to vand its penultimate vertex Pv for every vertex v in VInitialize (Q) //initialize vertex priority queue to empty

for every vertex v in V dodv←∞; Pv←NULLInsert (q, v, dv) //initialize vertex priority in the priority queue

ds←0; decrease (Q, s,ds) //update priority of s with ds

Vt←Φfor i←0 to |V|-1 do

u*←DeleteMin(Q) //delete the minimum priority element Vt←Vt U {u*}

For every vertex u in V-Vt that is adjacent to u* do if du* +w (u*, u) <du

dudu*+w (u*, u); Puu*Decrease (Q, u, du)

24

Page 25: Adalab Manual

Lab Manual: Algorithms Laboratory

/* DIJKSTRA */#include<stdio.h>#include<process.h>#include<conio.h>

void dijkstra(int n,int cost[10][10],int src){

int i,j,u,v,d[10],s[10],min;for(i=1;i<=n;i++){

d[i] = cost[src][i];s[i] = 0;

}s[src] = 1;for(i=1;i<=n;i++){

min=9999;for(j=1;j<=n;j++){

if(s[j]==0 && d[j]<min){

min=d[j];u=j;

}}s[u]=1;for(v=1;v<=n;v++){

if(s[v] == 0){

if(d[u]+cost[u][v]<d[v]){ d[v]=d[u]+cost[u][v];}

}}

}printf("\n The shortest paths are: \n");for(i=1;i<=n;i++){

printf("%d -- > %d = %d \n",src,i,d[i]);}

}

25

Page 26: Adalab Manual

Lab Manual: Algorithms Laboratory

void main(){

int i,j,n,cost[10][10],d[10],s[10],src;clrscr();printf("\n Enter the number of nodes :");scanf("%d",&n);printf("\n Enter the cost adjacency matrix:\n");for(i=1;i<=n;i++){

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

scanf("%d",&cost[i][j]);}

}printf("\n Enter the source:");scanf("%d",&src);dijkstra(n,cost,src);getch();

}

/******************** OUTPUT ****************

Enter the number of nodes :6

Enter the cost adjacency matrix:0 15 10 9999 45 99999999 0 15 9999 20 999920 9999 0 20 9999 99999999 10 9999 0 35 99999999 9999 9999 30 0 99999999 9999 9999 4 9999 0

Enter the source:6

The shortest paths are:6 -- > 1 = 496 -- > 2 = 146 -- > 3 = 296 -- > 4 = 46 -- > 5 = 346 -- > 6 = 0*******************************************/

26

Page 27: Adalab Manual

Lab Manual: Algorithms Laboratory

VIII. Sort a given set of elements using Quick sort method and determine the time required sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n.

Design Strategy: Divide and Conquer

ALGORITHM Quicksort (A [l...r]) // Sorts a subarray by quicksort //Input: a subarray A [l..r] Of A [0...n-1], defined by its left and right indices l and r //Output: the subarray A [l...r] sorted in non decreasing order if l < r s← partition (A [l..r]) // s is a split position Quicksort (A [l...s-1]) Quicksort (A [s+1...r]) ALGORITHM Partition (A [l...r]) // Partitions a subarray by using its first element as a pivot //Input: a subarray A [l...r] of A [0...n-1], defined by its left and right indices l and r (l<r) //Output: a partition of A [l...r], with 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

27

Page 28: Adalab Manual

Lab Manual: Algorithms Laboratory

/* QUICK SORT */#include<stdio.h>#include<conio.h>#include<process.h>#include<time.h>int a[10];clock_t start,end;int partition(int low,int high){

int i,j,temp,key;key=a[low];i=low+1;j=high;

while(1){

while(i<=high && key>= a[i])i++;

while(key<a[j])j--;

if(i<j){

temp=a[i];a[i]=a[j];a[j]=temp;

}else{

temp=a[low];a[low]=a[j];a[j]=temp;return j;

}}

}

void qsort(int low,int high){

int j;if(low<high){

j=partition(low,high);qsort(low,j-1);qsort(j+1,high);

}}

28

Page 29: Adalab Manual

Lab Manual: Algorithms Laboratory

void main(){

int i,n;clrscr();

printf("\n Enter the no. of elements in the vector : ");scanf("%d",&n);

printf("\n Enter the elements : ");for(i=0;i<n;i++)

scanf("%d",&a[i]);

start=clock();qsort(0,n-1);end=clock();

printf("\n\n The Sorted elements are : ");for(i=0;i<n;i++)

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

printf("\n\n Time taken is : %f \n",(start-end)/CLK_TCK);getch();

}

/***************************** OUTPUT ****************************

Enter the no. of elements in the vector : 5 Enter the elements : 88 -1 0 45 22 The Sorted elements are : -1 0 22 45 88 Time taken is : 0.000000

******************************************************************/

29

Page 30: Adalab Manual

Lab Manual: Algorithms Laboratory

IX. Find Minimum Cost Spanning Tree of given undirected graph using Kruskal’s algorithm.

Design Strategy: Greedy method. ALGORITHM kruskal(G) //Kruskal’s algorithm for constructing a minimum spanning tree // Input: A weighted connected graph G=V, E // Output: ET , the set of edges composing a minimum spanning tree of G Sort E in nondecreasing order of the edge weights w(ei1)<=…<=w(ei|E|) ET ; ecounter 0 //initialise the set of tree edges and its size k 0 //initialise the number of processed edges while ecounter < |V| - 1 k k+1 if ET {eik}is acyclic ET ET {eik}; ecounter ecounter+1

return ET

30

Page 31: Adalab Manual

Lab Manual: Algorithms Laboratory

/* KRUSKALS ALGORITHM */#include<stdio.h>#include<conio.h>int find(int v,int parent[]){

while(parent[v] != v){

v = parent[v];}return v;

}

void union_ij(int i,int j,int parent[]){

if(i<j)parent[j] = i;

elseparent[i] = j;

}

void kruskal(int n,int a[10][10]){

int count,k,min,sum,i,j,t[10][10],u,v,parent[10],y,st[10];count=0;k=0;sum=0;y=0;for(i=1;i<=n;i++)

parent[i] = i;while(count != n-1){

min = 9999;for(i=1;i<=n;i++){

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

if(a[i][j] < min && a[i][j] != 0){

min = a[i][j];u=i;v=j;

}}

}i = find(u,parent);j = find(v,parent);

31

Page 32: Adalab Manual

Lab Manual: Algorithms Laboratory

if(i != j){

t[k][0] = u;t[k][1] = v;k++;count++;st[y]=a[u][v];sum+=a[u][v];union_ij(i,j,parent);y++;

}a[u][v] = a[v][u] = 9999;

}if(count == n-1){

printf("\n Spanning tree exists \n");printf("\n Spanning tree is shown below \n\n");for(i=0;i<n-1;i++){

printf("\t Edge \t (%d,%d) = %d \n",t[i][0],t[i][1],st[i]);}printf("\n\t Minimum Cost of the spanning tree = %d",sum);

}else

printf("\n Spanning tree does not exist");}

void main(){

int n,a[10][10],i,j;clrscr();printf("\n Enter the no. of nodes in the graph : ");scanf("%d",&n);printf("\n Enter the adjacency matrix of the graph : \n");for(i=1;i<=n;i++){

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

scanf("%d",&a[i][j]);}

}kruskal(n,a);getch();

}

32

Page 33: Adalab Manual

Lab Manual: Algorithms Laboratory

/***************** OUTPUT ***********************

Enter the no. of nodes in the graph : 5 Enter the adjacency matrix of the graph : 0 5 999 6 999 5 0 1 3 999 999 1 0 4 6 6 3 4 0 2 999 999 6 2 0 Spanning tree exists Spanning tree is shown below

Edge (2,3) = 1 Edge (4,5) = 2 Edge (2,4) = 3 Edge (1,2) = 5

Minimum Cost of the spanning tree = 11

*************************************************/

33

Page 34: Adalab Manual

Lab Manual: Algorithms Laboratory

X. a) Print all the nodes reachable from a given starting node in a digraph using BFS method.

b) Check whether a given graph is connected of not using DFS method.

a) Print all the nodes reachable from a given starting node in a digraph using BFS method.

Design and Strategy: Decrease and Conquer.

ALGORI THM BFS(G)//Implements a breadth-first search traversal of a given graph//Input:Graph G=<V, E>//Output:Graph G with its vetices marked with consecutive integers in the order they have //been visited by the BFS traversalmark each vetex with 0 as a mark of being “unvisited”count←0for each vertex v in V do

if v is marked with 0bfs(v)

bfs(v)//visits all the unvisited vertices connected to vertex v and assigns them the numbers in//the order they are visited via global variable countcount←count+1; mark v with count and initailize a queue with vwhile the queue is not empty do

for each vertex w in V adjacent to the front’s vertex v doif w is marked with 0

count←count+1;mark w with countadd w to the queue

remove vertex v from the front of the queue

34

Page 35: Adalab Manual

Lab Manual: Algorithms Laboratory

PROGRAM TO PRINT NODES FROM THE GIVEN SOURCE USING BFS METHOD #include<stdio.h>#include<conio.h>

int a[10][10],vis[10],k,n;void bfs(int);

void main(){

int i,j,source;clrscr();printf("\n Enter the no. of vertices : ");scanf("%d",&n);printf("\n Enter the Adajacency matrix : \n");for(i=1;i<=n;i++){

for(j=1;j<=n;j++)scanf("%d",&a[i][j]);vis[i]=0;

}printf("\n Enter the source vertex : ");scanf("%d",&source);printf("\n Nodes reachable from %d is : ",source);bfs(source);getch();

}void bfs(int v){

int q[10],r=1,f=1,i,u;q[r]=v;vis[v]=1;while(f<=r){

u=q[f];printf(" %d ",u);for(i=1;i<=n;i++){

if(a[u][i] == 1 && vis[i] == 0){

q[++r]=i;vis[i]=1;

}}f++;

}}

35

Page 36: Adalab Manual

Lab Manual: Algorithms Laboratory

/****************************** OUTPUT **************************

Enter the no. of vertices : 4 Enter the Adajacency matrix : 0 1 0 1 0 0 1 0 0 0 0 0 0 0 1 0 Enter the source vertex : 1 Nodes reachable from 1 is : 1 2 4 3

Enter the no. of vertices : 4 Enter the Adajacency matrix : 0 1 1 0 1 0 0 1 1 0 0 0 0 1 0 0 Enter the source vertex : 2 Nodes reachable from 2 is : 2 1 4 3

****************************************************************/

36

Page 37: Adalab Manual

Lab Manual: Algorithms Laboratory

b) Check whether a given graph is connected of not using DFS method.

Design strategy: Decrease and Conquer

ALGORITHM DFS(G)//Implements a depth-first search traversal of a given graph

//Input: Graph G=<V, E>

//Output: Graph G with its vertices marked with consecutive integers in the order they //have been first encountered by the DFS traversal

mark each vertex in V with 0 as a mark of being “unvisited”Count←0 connect←0for each vertex v in V do

if v is marked with 0dfs(v) connect←connect+1

dfs(v)

//visits recursively all the unvisited vertices connected to vertex v and assigns them the

//numbers in the order they are encountered via global variable countcount←count+1 ; mark v with countfor each vertex w in V adjacent to v do

if w is marked with 0dfs(w)

if connect>1 then graph is disconnected else graph is connected

37

Page 38: Adalab Manual

Lab Manual: Algorithms Laboratory

/* GRAPH CONNECTED OR NOT */#include<stdio.h>#include<conio.h>

int a[10][10],vis[10],n;

void dfs(int);

void main(){

int i,j,source;clrscr();printf("\n Enter the no. of vertices : ");scanf("%d",&n);printf("\n Enter the adjacency matrix : \n");

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

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

scanf("%d",&a[i][j]);}

}

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

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

vis[j]=0;dfs(source);for(j=1;j<=n;j++){ if(vis[j]==0) { printf("\n\n!!! GIVEN GRAPH IS NOT CONNECTED !!! \n\n"); getch(); exit(0); }}

}

printf("\n\n!!! GIVEN GRAPH IS CONNECTED !!! \n\n");getch();

}

38

Page 39: Adalab Manual

Lab Manual: Algorithms Laboratory

void dfs(int v){

int i;vis[v]=1;for(i=1;i<=n;i++){

if(a[v][i]==1 && vis[i]==0)dfs(i);

}}

/******************************* OUTPUT **************************

Enter the no. of vertices : 4 Enter the adjacency matrix : 0 1 0 1 0 0 1 0 0 0 0 0 0 0 1 0 !!! GIVEN GRAPH IS NOT CONNECTED !!!

Enter the no. of vertices : 4 Enter the adjacency matrix : 0 1 0 0 0 0 1 0 0 0 0 1 1 0 0 0 !!! GIVEN GRAPH IS CONNECTED !!!

*****************************************************************/

39

Page 40: Adalab Manual

Lab Manual: Algorithms Laboratory

XI. Find a subset of a given set S = {s1,s2,……………,sn} of n positive integers whose sum is equal to a given positive integer d. For example, if S = {1,2,5,6,8} and d=9 there are two solutions {1,2,6} and {1,8}. A suitable message is to be displayed if the given problem instance doesn’t have a problem.

Design strategy: Back tracking

ALGORITHM subset(s, k, r) //Find all the subset of w [1: n] that sum to m. //The values of x [j], 1jk, have already been determined. // s = j=1to k-1 w [j]*x [j] and r = j=k to n w [j]. //The w [j]’s are in the nondecreasing order. //It is assumed that w [1]m and i=1 to n w [i]m.{ //Generate left child. Note: s + w [k]m since Bk-1is true

x [k]: =1; if (s + w [k] = m) then write (x[1: k]) ; //subset found //There is no recursive call here as w [j]>0, 1jn. else if(s + w [k] +w[k+1]m) then subset (s + w [k], k+1, r – w [k]); //Generate right child and evaluate Bk. if((s + r – w [k]m) and (s + w [k+1]m)) then { x [k]:= 0; subset (s, k+1, r – w [k]); }}

40

Page 41: Adalab Manual

Lab Manual: Algorithms Laboratory

/* FIND A SUBSET OF GIVEN SET OF N POSITIVE INTEGERS */#include<stdio.h>#include<conio.h>void subset(int n,int d,int w[]){

int s,k,i,x[10],count=0;for(i=1;i<=n;i++)

x[i] = 0;s=0;k=1;x[k]=1;

while(1){

if(k<=n && x[k]==1){

if(s+w[k] == d){

printf("\n Solution %d is : ",++count);for(i=1;i<=n;i++){

if(x[i] == 1)printf("%d\t",w[i]);

}printf("\n\n");x[k]=0;

}else if(s+w[k]<d)

s+=w[k];else

x[k]=0;}else{

k--;while(k>0 && x[k]==0)

k--;if(k==0)

break;x[k]=0;s=s-w[k];

}k=k+1;x[k]=1;

}}

41

Page 42: Adalab Manual

Lab Manual: Algorithms Laboratory

void main(){

int i,sum,d,n,w[10];printf("\n Enter the value of n : ");scanf("%d",&n);printf("\n Enter the set in increasing order : ");for(i=1;i<=n;i++)

scanf("%d",&w[i]);printf("\n Enter the maximum subset values(sum) : ");

scanf("%d",&d);for(i=1;i<=n;i++)sum+=w[i];if(sum < d || w[1] > d){

printf("\n\n No Solution exists \n\n");return;

}subset(n,d,w);getch();

}

/***************************** OUTPUT **************************

Enter the value of n : 5 Enter the set in increasing order : 1 2 5 6 8 Enter the maximum subset values(sum) : 9 Solution 1 is : 1 2 6 Solution 2 is : 1 8

****************************************************************/

42

Page 43: Adalab Manual

Lab Manual: Algorithms Laboratory

XII. a) Implement Horspool algorithm for String Matching. b) Find the Binomial Co-effient using Dynamic Programming.

a) Implement Horspool algorithm for String Matching.Design strategy: Space and Time TradeoffsALGORITHM horspoolmatching(p[0…m-1],T[0…n-1]) //Implements horspool’s algorithm for string matching//input: pattern p[0…m-1] and text T[0…n-1]//output: the index of the left end of the first matching substring or -1 if there are no //matches.shiftTable( p[0…m-1]) //generate table of shiftsi←m-1while i≤n-1 do

k←0while k≤m-1 and p[m-1-k]=T[i-k] k←k+1if k=m

return i-m+1else i←i+Table[T[i]]

return -1ALGORITHM shiftTable(p[0…m-1])// Fills the shift table used by Horspool’s and Boyer-Moore algorithms // Input: pattern p[0…m-1] and an alphabet of possible characters // Output: Table[0…size-1] indexed by the alphabet’s characters and filled with shift //sizes computed by formula

initialize all the elements of Table with mfor j←0 to m-2 do Table[p[j]]←m-1-jreturn Table

INPUT: pattern P and text T TEXT: JIM_SAW_ME_IN-A_BARBERSSHOPPATTERN: BARBER.

OUTPUT:The shift table is filled as follows

Character A B C D E F . . . . . . R ………… Z -Shift t(c) 4 2 6 6 1 6 6 3 6 6 6

The actual search in a particular text proceeds asJ I M _ S A W _M E_ I N – A _ B A R B E R S S H O PB A R B E R B A R B E R B A R BE R B A R B E R BAR B E R BARB E R

The algorithm returns index of the left end of the first matching substring or -1 if there are no matches.

43

Page 44: Adalab Manual

Lab Manual: Algorithms Laboratory

/* HORSPOOL */#include<stdio.h>#include<conio.h>#include<string.h>#include<process.h>void shifttable(char p[],int t[]){

int m,i;m=strlen(p);for(i=0;i<128;i++)

t[i]=m;for(i=0;i<=m-2;i++)

t[p[i]]=m-1-i;}int horspool(char p[],char t[]){

int m,n,i,k,s[256];shifttable(p,s);m=strlen(p);n=strlen(t);i=m-1;while(i<=n-1){

k=1;while(k<=m-1 && t[i-k] == p[m-1-k])

k++;if(k==m)

return(i-m+1);i=i+s[t[i]];

}return -1;

}void main(){

char p[20],t[40];int pos; clrscr();printf("\n\n Enter the String : ");gets(t);printf("\n\n Enter the Pattern String : ");gets(p);pos=horspool(p,t);if(pos==-1)

printf("\n\n STRING NOT FOUND \n\n");else printf("\n\n STRING FOUND AT %d POSITION \n\n",pos+1);getch();

}

44

Page 45: Adalab Manual

Lab Manual: Algorithms Laboratory

/**************************** OUTPUT *************************

Enter the String : JIM SAW ME IN BARBER SHOP

Enter the Pattern String : BARBER

STRING FOUND AT 15 POSITION

Enter the String : JIM SAW ME IN BARBER SHOP

Enter the Pattern String : JOHN

STRING NOT FOUND

*************************************************************/

45

Page 46: Adalab Manual

Lab Manual: Algorithms Laboratory

b) Find the Binomial Co-effient using Dynamic Programming.

Design strategy: Dynamic programming ALGORITHM binomial (n, k) //computes C (n, k) by the dynamic programming algorithm //input: a pair of non-negative integers n ≥k ≥0 //output: the value of C (n, k) for i0 to n do for j0 to min (i, k) do if j=0 or j=i C[i, j]1 else C[i, j] C[i-1, j-1]+ C[i-1, j] return C[n, k]

INPUT: a pair of non-negative integer’s n ≥k ≥0 n= 6 k= 3

OUTPUT:

0 1 2 30 11 1 12 1 2 13 1 3 3 14 1 4 6 45 1 5 10 106 1 6 15 20

The value C (6,3) = 20

/* BINOMIAL CO-EFFICIENT */

46

Page 47: Adalab Manual

Lab Manual: Algorithms Laboratory

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

int nck(int,int);int min(int,int);

void main(){

int n,r,y;clrscr();printf("\n Enter the values 'n' and 'r' : ");scanf("%d %d",&n,&r);y=nck(n,r);if(y==-1)

printf("\n\n Invalid input \n\n");else{

printf("\n\n Value of nCr is : ");printf("%d",y);

}getch();

}

int nck(int n,int r){

int c[10][10],i,j;if(n<r)

return -1;else{

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

for(j=0;j<=min(i,r);j++){

if(j==0 || i==j)c[i][j]=1;

elsec[i][j]=c[i-1][j-1]+c[i-1][j];

}}

return c[n][r];}

}

int min(int a,int b)

47

Page 48: Adalab Manual

Lab Manual: Algorithms Laboratory

{if(a<b)

return a;else

return b;}

/******************************* OUTPUT **************************

Enter the values 'n' and 'r' : 6 3 Value of nCr is : 20 *****************************************************************/

48

Page 49: Adalab Manual

Lab Manual: Algorithms Laboratory

XIII. Find Minimum Cost Spanning Tree of given undirected graph using Prim’s algorithm.

Design Strategy: Greedy method ALGORITHM prim (G)

//prim’s algorithm for constructing a minimum spanning tree

// Input: A weighted connected graph G=V, E

// Output: ET , the set of edges composing a minimum spanning tree of G VT {v0} ET for i 1 to |V| -1 do find a minimum-weight edge e*=(v*, u*) among all edges (v, u) such that v is in VT and u is in V-VT

VT VT {u*} ET ET {e*}

return ET

/* PRIMS ALGORITHM */

49

Page 50: Adalab Manual

Lab Manual: Algorithms Laboratory

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

void prims(int n,int cost[10][10]){

int i,j,u,v,src,d[10],s[10],p[10],t[10][2],k,min,y,st[10],sum;src=0;min=9999;for(i=1;i<=n;i++){

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

if(cost[i][j] != 0 && cost[i][j] < min){

min=cost[i][j];src=i;

}}

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

d[i]=cost[src][i];s[i]=0;p[i]=src;

}s[src]=1;k=0;sum=0;y=0;for(i=2;i<=n;i++){

min=9999;u=-1;for(j=1;j<=n;j++){

if(s[j] == 0 && d[j] <= min){

min=d[j];u=j;

}}t[k][0]=p[u];t[k][1]=u;k++;st[y]=cost[u][p[u]];

50

Page 51: Adalab Manual

Lab Manual: Algorithms Laboratory

sum+=cost[u][p[u]];s[u]=1;y++;for(v=1;v<=n;v++){

if(s[v] == 0){

if(cost[u][v] < d[v]){

d[v]=cost[u][v];p[v]=u;

}}

}}if(sum>=9999)

printf("\n\n Spanning tree doesnot exist \n\n");else{

printf("\n\n SPANNING TREE EXISTS \n\n"); printf(" MINIMUM SPANNING TREE : \n\n"); for(i=0;i<n-1;i++) { printf("\t Edge (%d,%d) = %d\n",t[i][0],t[i][1],st[i]); } printf("\n The Minimum Cost of Spanning Tree = %d\n",sum);

}}void main(){

int n,i,j,cost[10][10];clrscr();printf("\n\n Enter the number of Vertices : ");scanf("%d",&n);printf("\n\n Enter the Cost Adjacency matrix : \n");for(i=1;i<=n;i++){

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

scanf("%d",&cost[i][j]);}

}prims(n,cost);getch();

}/****************************** OUTPUT ****************************

51

Page 52: Adalab Manual

Lab Manual: Algorithms Laboratory

Enter the number of Vertices : 6

Enter the Cost Adjacency matrix :0 60 10 9999 9999 999960 0 9999 20 40 7010 9999 0 9999 9999 509999 20 9999 0 999 809999 40 9999 9999 0 309999 70 50 80 30 0

SPANNING TREE EXISTS

MINIMUM SPANNING TREE :

Edge (1,3) = 10 Edge (3,6) = 50 Edge (6,5) = 30 Edge (5,2) = 40 Edge (2,4) = 20

The Minimum Cost of Spanning Tree = 150

******************************************************************/

52

Page 53: Adalab Manual

Lab Manual: Algorithms Laboratory

XIV. a) Implement Floyd’s algorithm for the All-Pairs-Shortest-Paths problem. b) Compute the transitive closure of a given directed graph using Warshall’s algorithm.

a) Implement Floyd’s algorithm for the All-Pairs-Shortest-Paths problem.

Design strategy: Dynamic programming.

ALGORITHM Floyd (W [1…n,1…n)//Implements Floyd’s algorithm for the all-pairs shortest –paths problem //Input: The weight matrix W of a graph//Output:The distance matrix of the shortest paths ‘lengths

D←W //is not necessary if W can be writtenfor k←1 to n do

for i←1 to n do for j←1 to n do

D[i,j]←min{D[i,j], D[ i,k] + D[k,j]}return D

INPUT: the weight graph w of a graph.

OUTPUT: The distance matrix of the shortest paths lengths

a b c da 0 1 3 8b ∞ 0 2 ∞c ∞ ∞ 0 ∞d ∞ ∞ 2 0

/* FLOYDS ALGORITHM */

a b c da 0 1 7 8b ∞ 0 2 9c ∞ ∞ 0 ∞d ∞ ∞ 2 0

7 2

2

a

c

b

d

1

8

53

9

Page 54: Adalab Manual

Lab Manual: Algorithms Laboratory

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

void floyd(int);

int min(int,int);int a[10][10],p[10][10],i,j,k;

void main(){

int n;clrscr();printf("\n Enter the no. of vertices : \n");scanf("%d",&n);printf("\n Enter the cost adjacency matrix of the graph...\n");printf("\n Enter 999 if edge is absent \n");for(i=1;i<=n;i++){

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

scanf("%d",&a[i][j]);p[i][j] = a[i][j];

}}

floyd(n);

printf("\n The all pair shortest path matrix is \n");for(i=1;i<=n;i++){

printf("\n");for(j=1;j<=n;j++){

printf(" %d ",p[i][j]);}

}getch();

}

void floyd(int n)

54

Page 55: Adalab Manual

Lab Manual: Algorithms Laboratory

{for(k=1;k<=n;k++){

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

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

p[i][j]=min(p[i][j],p[i][k]+p[k][j]);}

}}

}

int min(int a,int b){

if(a<b)return a;

elsereturn b;

}

/******************************** OUTPUT **********************

Enter the no. of vertices :4

Enter the cost adjacency matrix of the graph...

Enter 999 if edge is absent0 1 7 8999 0 2 999999 999 0 999999 999 2 0

The all pair shortest path matrix is

0 1 3 8 999 0 2 999 999 999 0 999 999 999 2 0

**************************************************************/

b) Compute the transitive closure of a given directed graph using Warshall’s algorithm.

55

Page 56: Adalab Manual

Lab Manual: Algorithms Laboratory

Design strategy: Dynamic Programming

ALGORITHM Warshall (A [1…n, 1…n])//Implements Warshall’s algorithm for computing the transitive closure// Input: The adjacency matrix A of a digraph with n vertices//Output: The transitive closure of the digraph

R (0) ←A

for k← to n do for i← to n do

for j← to n do R (k) [i, j] ←R (k-1) [i, j] or R (k-1) [i, k] and R (k-1) [k, j]

return R (n)

INPUT: The adjacency matrix A of a digraph with n vertices

OUTPUT: The transitive closure of the digraph

a b c d

a 0 1 1 1

b 0 0 1 0

c 0 0 0 0

d 0 0 1 0

a b c d

a 0 1 0 1

b 0 0 1 0

c 0 0 0 0

d 0 0 1 0

a

d

b

c

56

Page 57: Adalab Manual

Lab Manual: Algorithms Laboratory

/* WARSHALL ALGORITHM */#include<stdio.h>void warshall(int);int i,j,p[10][10],a[10][10];void main(){

int n;clrscr();printf("\n Enter the no. of vertices : ");scanf("%d",&n);printf("\n Enter the adjacency matrix : \n");for(i=0;i<n;i++){

for(j=0;j<n;j++){

scanf("%d",&a[i][j]);p[i][j]=a[i][j];

}}warshall(n);printf("\n The transitive closure is : ");for(i=0;i<n;i++){

printf("\n");for(j=0;j<n;j++){

printf(" %d ",p[i][j]);}

}getch();

}void warshall(int n){

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

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

for(j=0;j<n;j++){

if(p[i][j]!=1 && p[i][k]==1 && p[k][j]==1)p[i][j]=1;

}}

}}

57

Page 58: Adalab Manual

Lab Manual: Algorithms Laboratory

/************************ OUTPUT *************************

Enter the no. of vertices : 4 Enter the adjacency matrix : 0 1 0 1 0 0 1 0 0 0 0 0 0 0 1 0 The transitive closure is : 0 1 1 1 0 0 1 0 0 0 0 0 0 0 1 0

**********************************************************/

58

Page 59: Adalab Manual

Lab Manual: Algorithms Laboratory

XV. Implement N Queen’s problem using Back Tracking.

Design Strategy: Back Tracking. ALGORITHM Place (k)

//Implements N-Queen using Backtracking procedure to find whether a new Queen can be placed//procedure returns true if a queen can be placed in kth row & X (k) th column otherwise it returns //false. X is a global array whose first k values have been set ABS(r) returns absolute value of r

Global X (1: k); integer i, k

for i←1 to k do if X (i)=X(k) // two in same column

or ABS(X(i)-X(k))=ABS(i-k) //in the same diagonal then return false endifrepeat return true

ALGORITHM nqueens(n)//This procedure prints all possible placements of n queens on an n*n chessboard so that they are //non attacking.

Integer k, n, X (1, n)

X(!)←0; k←1 //k is current row X(k) current column

While k>0 do //for all rows doX(k)←X(k)+1 //move to next column

While X(k)<=n & not place(k) do //can this queen can be placed X(k)←X(k)+1

repeatif X(k)<=n //a possible is found

then if k=n //is a solution completethen print(x) //if yes ,print the array

else k←k+1 X(k)←0//go to the new rowendif

else k←k-1 //backtrackendifrepeat

59

Page 60: Adalab Manual

Lab Manual: Algorithms Laboratory

/* NQUEENS BACK TRACKING */

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

int canplace(int r,int c[5]){

int i,j;for(i=0;i<r;i++){

if(c[i]==c[r] || (c[i]-c[r]) == abs(i-r))return(0);

}return(1);

}

void display(int c[50],int n){

int i,j;char cb[10][10];for(i=0;i<n;i++)

for(j=0;j<n;j++)cb[i][j]='-';

for(i=0;i<n;i++)cb[i][c[i]]='Q';

printf("\n");for(i=0;i<n;i++){

for(j=0;j<n;j++)printf(" %c ",cb[i][j]);printf("\n");

}}

void nqueen(int n){

int r,c[50];c[0]=-1;r=0;while(r>=0){

c[r]++;while(c[r]<n && !canplace(r,c))

c[r]++;

60

Page 61: Adalab Manual

Lab Manual: Algorithms Laboratory

if(c[r]<n){

if(r==n-1){

display(c,n);printf("\n");

}else{

r++;c[r]=-1;

}}else

r--;}

}

void main(){

int n;clrscr();printf("\n\n Enter the number of Queens : ");scanf("%d",&n);nqueen(n);getch();

}

61

Page 62: Adalab Manual

Lab Manual: Algorithms Laboratory

/*************************** OUTPUT **************************

Enter the number of Queens : 4

Q - - - - Q - - - - Q - - - - Q

Q - - - - - Q - - - - Q - Q - -

Q - - - - - - Q - Q - - - - Q -

- Q - - - - Q - Q - - - - - - Q

- Q - - - - - Q Q - - - - - Q -

- - Q - Q - - - - Q - - - - - Q

- - Q - Q - - - - - - Q - Q - -

*************************************************************/

62