Anda di halaman 1dari 63

Lab Manual: Algorithms Laboratory CONTENT SHEET SLNO. 1.

EXPERIMENT NAME 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. 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. 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. 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. 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. 7. 8. Implement 0/1 Knapsack problem using dynamic programming. From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstras algorithm. 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. Find Minimum Cost Spanning Tree of given undirected graph using Kruskals algorithm. 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. PAGE NO.

2.

3.

4.

5.

9. 10.

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 doesnt have a problem. a) Implement Horspool algorithm for String Matching. b) Find the Binomial Co-efficient using Dynamic Programming. 13. 14. Find Minimum Cost Spanning Tree of given undirected graph using Prims algorithm. a) Implement Floyds algorithm for the All-Pairs-Shortest-Paths problem. b) Compute the transitive closure of a given directed graph using Warshalls algorithm. 15. Implement N Queens problem using Back Tracking.

12.

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[lr],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 arrays 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)

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; else return 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 : "); scanf("%d",&c);

Lab Manual: Algorithms Laboratory 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

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

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 heap Deleting roots key with the last key k of the heap can be done by the following algorithm. Step 1: exchange the roots key with the last key k of the heap. Step 2: Decrease the heaps 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[1n] for i|_n/2_| down to 1 do ki; v H[k] heapfalse While not heap and 2* k<=n do J2*k if j<n //there are two children if H[j]<H[j+1] jj+1 if v>=H[j] heaptrue else H[k]H[j]: kj H[k]v

/* HEAP SORT */

Lab Manual: Algorithms Laboratory #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; } void heap_sort(int a[],int n)

Lab Manual: Algorithms Laboratory { 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 The sorted array Time taken is : 0.000000 **************************************************/ : 10 98 56 54 67 : 10 54 56 67 98

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 ; j0 ; k0 while i < p and j < q do if B[i] <= C[j] A [k] B [i]; ii+1 else A [k]C [j]; jj+1 kk+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 order if 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)

/* MERGE SORT */

10

Lab Manual: Algorithms Laboratory #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++]; else c[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]; } void merge(int low,int high)

11

Lab Manual: Algorithms Laboratory { 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

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]

/* SELECTION SORT */

13

Lab Manual: Algorithms Laboratory #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 The sorted array is :9 : 76 45 87 34 09 34 45 76 87

The Time taken is : 0.000000 ***************************************************************/ V. a) Obtain the Topological ordering of vertices in a given digraph.

14

Lab Manual: Algorithms Laboratory

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 1 3 2 5 4

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

15

Lab Manual: Algorithms Laboratory

#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(); }

void dfs(int v)

16

Lab Manual: Algorithms Laboratory { 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

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 Count0 for each vertex v in V do if v is marked with 0 dfs (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 count countcount+1 ; mark v with count for each vertex w in V adjacent to v do if w is marked with 0 dfs(w)

18

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

Lab Manual: Algorithms Laboratory /*************************** OUTPUT **************************** Enter the no. of vertices Enter the adjacency matrix 0101 0010 0000 0010 Enter the source vertex Nodes reachable from 1 vertex is Enter the no. of vertices Enter the adjacency matrix 0110 1001 1000 0100 Enter the source vertex Nodes reachable from 2 vertex is :4 : :4 :

:1 : 1 2 3 4

:2 : 2 1 3 4

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

20

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 [1n], values [1n] and table v[0n,0w] whose entries are initialized with -1 except for row 0 and column 0 initialized with 0s if v[i,j] <0 if j<weights[i] valueMFKnapsack(i-1,j) else valuemax(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 2 3 4 OUTPUT: i 0 W1=1, v1=20 W2=2,v2=60 W3=3,v3=20 W4=1, v4=30 1 2 3 4 0 0 0 0 0 0 1 2 3 1 1 0 20 20 20 30 2 0 20 60 60 60 20 60 20 30 3 0 20 80 80 90 4 0 20 80 80 110 5 0 20 80 80 110

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

21

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]; else v[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

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; else return 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 20 2 60 3 20 1 30 0 0 0 0 0 0 0 20 20 20 20 20 0 20 60 80 80 80 0 20 60 80 80 80 0 30 60 90 110 110 Optimum Profit is : 110 Objects selected are : 1 2 4 ************************************************************/

: ");

23

Lab Manual: Algorithms Laboratory VII. From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstras algorithm. Design strategy: Greedy Method ALGORITHM dijkstras (G, s) //dijkstras 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 v and its penultimate vertex Pv for every vertex v in V Initialize (Q) //initialize vertex priority queue to empty for every vertex v in V do dv; PvNULL Insert (q, v, dv) //initialize vertex priority in the priority queue ds0; decrease (Q, s,ds) //update priority of s with ds Vt for i0 to |V|-1 do u*DeleteMin(Q) //delete the minimum priority element VtVt 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

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

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 9999 9999 0 15 9999 20 9999 20 9999 0 20 9999 9999 9999 10 9999 0 35 9999 9999 9999 9999 30 0 9999 9999 9999 9999 4 9999 0 Enter the source:6 The shortest paths are: 6 -- > 1 = 49 6 -- > 2 = 14 6 -- > 3 = 29 6 -- > 4 = 4 6 -- > 5 = 34 6 -- > 6 = 0 *******************************************/

26

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 functions value pa[l] i l ; j r+1 repeat repeat i i+1 until A[i]>=p repeat jj-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

/* QUICK SORT */

27

Lab Manual: Algorithms Laboratory #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); } } void main()

28

Lab Manual: Algorithms Laboratory { 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

Lab Manual: Algorithms Laboratory IX. Find Minimum Cost Spanning Tree of given undirected graph using Kruskals algorithm. Design Strategy: Greedy method. ALGORITHM kruskal(G) //Kruskals 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

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; else parent[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

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 for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { scanf("%d",&a[i][j]); } } kruskal(n,a); getch(); }

: "); : \n");

32

Lab Manual: Algorithms Laboratory /***************** OUTPUT *********************** Enter the no. of nodes in the graph Enter the adjacency matrix of the graph 0 5 999 6 999 5 0 1 3 999 999 1 0 4 6 63402 999 999 6 2 0 Spanning tree exists Spanning tree is shown below Edge Edge Edge Edge (2,3) = 1 (4,5) = 2 (2,4) = 3 (1,2) = 5 :5 :

Minimum Cost of the spanning tree = 11 *************************************************/

33

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 traversal mark each vetex with 0 as a mark of being unvisited count0 for each vertex v in V do if v is marked with 0 bfs(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 count countcount+1; mark v with count and initailize a queue with v while the queue is not empty do for each vertex w in V adjacent to the fronts vertex v do if w is marked with 0 countcount+1;mark w with count add w to the queue remove vertex v from the front of the queue

34

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

Lab Manual: Algorithms Laboratory /****************************** OUTPUT ************************** Enter the no. of vertices :4

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

Enter the Adajacency matrix : 0110 1001 1000 0100 Enter the source vertex Nodes reachable from 2 is :2 : 2 1 4 3

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

36

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 Count0 connect0 for each vertex v in V do if v is marked with 0 dfs(v) connectconnect+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 count countcount+1 ; mark v with count for each vertex w in V adjacent to v do if w is marked with 0 dfs(w) if connect>1 then graph is disconnected else graph is connected

37

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 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(); }

: "); : \n");

38

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 Enter the adjacency matrix 0101 0010 0000 0010 :4 :

!!! GIVEN GRAPH IS NOT CONNECTED !!! Enter the no. of vertices Enter the adjacency matrix 0100 0010 0001 1000 :4 :

!!! GIVEN GRAPH IS CONNECTED !!! *****************************************************************/

39

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 doesnt 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], 1[ j[ k, 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, 1[ j[ n. 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

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

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 :12568

Enter the set in increasing order

Enter the maximum subset values(sum) : 9 Solution 1 is : 1 Solution 2 is : 1 2 8 6

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

42

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 Tradeoffs ALGORITHM horspoolmatching(p[0m-1],T[0n-1]) //Implements horspools algorithm for string matching //input: pattern p[0m-1] and text T[0n-1] //output: the index of the left end of the first matching substring or -1 if there are no //matches. shiftTable( p[0m-1]) //generate table of shifts im-1 while in-1 do k0 while km-1 and p[m-1-k]=T[i-k] kk+1 if k=m return i-m+1 else ii+Table[T[i]] return -1 ALGORITHM shiftTable(p[0m-1]) // Fills the shift table used by Horspools and Boyer-Moore algorithms // Input: pattern p[0m-1] and an alphabet of possible characters // Output: Table[0size-1] indexed by the alphabets characters and filled with shift //sizes computed by formula initialize all the elements of Table with m for j0 to m-2 do Table[p[j]]m-1-j return Table INPUT: pattern P and text T TEXT: JIM_SAW_ME_IN-A_BARBERSSHOP PATTERN: BARBER. OUTPUT: The shift table is filled as follows Character A B C D E F . . . . . . R Shift t(c) 4 2 6 6 1 6 6 3 The actual search in a particular text proceeds as J I M _ S A W _M E_ I N A _ B A R B E R S S H O P BA RB E R BARBER B A R BE R BARBER BAR B E R BARB E R

Z 6 6

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

43

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

Lab Manual: Algorithms Laboratory /**************************** OUTPUT ************************* Enter the String Enter the Pattern String : JIM SAW ME IN BARBER SHOP : BARBER

STRING FOUND AT 15 POSITION Enter the String Enter the Pattern String STRING NOT FOUND *************************************************************/ : JIM SAW ME IN BARBER SHOP : JOHN

45

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 integers n k 0 n= 6 k= 3 OUTPUT: 0 1 2 3 4 5 6 0 1 1 1 1 1 1 1 1 1 2 3 4 5 6 2 3

1 3 6 10 15

1 4 10 20

The value C (6,3) = 20

46

Lab Manual: Algorithms Laboratory /* BINOMIAL CO-EFFICIENT */ #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; else c[i][j]=c[i-1][j-1]+c[i-1][j]; } } return c[n][r]; } }

47

Lab Manual: Algorithms Laboratory int min(int a,int b) { if(a<b) return a; else return b; } /******************************* OUTPUT ************************** Enter the values 'n' and 'r' : 6 3 Value of nCr is : 20

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

48

Lab Manual: Algorithms Laboratory

XIII. Find Minimum Cost Spanning Tree of given undirected graph using Prims algorithm. Design Strategy: Greedy method ALGORITHM prim (G) //prims 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

49

Lab Manual: Algorithms Laboratory /* PRIMS ALGORITHM */ #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++;

50

Lab Manual: Algorithms Laboratory st[y]=cost[u][p[u]]; 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(); }

51

Lab Manual: Algorithms Laboratory /****************************** OUTPUT **************************** Enter the number of Vertices : 6 Enter the Cost Adjacency matrix 0 60 10 9999 9999 9999 60 0 9999 20 40 70 10 9999 0 9999 9999 50 9999 20 9999 0 999 80 9999 40 9999 9999 0 30 9999 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

Lab Manual: Algorithms Laboratory

XIV. a) Implement Floyds algorithm for the All-Pairs-Shortest-Paths problem. b) Compute the transitive closure of a given directed graph using Warshalls algorithm. a) Implement Floyds algorithm for the All-Pairs-Shortest-Paths problem. Design strategy: Dynamic programming. ALGORITHM Floyd (W [1n,1n) //Implements Floyds 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 DW //is not necessary if W can be written for k1 to n do for i1 to n do for j1 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.

a 7 c 2

b 8 9 d a b c d

a 0

b 1 0

c 7 2 0 2

d 8 9 0

OUTPUT: The distance matrix of the shortest paths lengths a 0 b 1 0 c 3 2 0 2 d 8 0

a b c d

53

Lab Manual: Algorithms Laboratory /* FLOYDS ALGORITHM */ #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(); }

54

Lab Manual: Algorithms Laboratory void floyd(int n) { 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; else return b; } /******************************** OUTPUT ********************** Enter the no. of vertices : 4 Enter the cost adjacency matrix of the graph... Enter 999 if edge is absent 0178 999 0 2 999 999 999 0 999 999 999 2 0 The all pair shortest path matrix is 0 1 999 999 999 3 8 0 2 999 999 0 999 999 2 0

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

55

Lab Manual: Algorithms Laboratory b) Compute the transitive closure of a given directed graph using Warshalls algorithm. Design strategy: Dynamic Programming ALGORITHM Warshall (A [1n, 1n]) //Implements Warshalls 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 a b a b c d a 0 0 0 0 b 1 0 0 0 c 0 1 0 1 d 1 0 0 0

OUTPUT: The transitive closure of the digraph a 0 0 0 0 b 1 0 0 0 c 1 1 0 1 d 1 0 0 0

a b c d

56

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

Lab Manual: Algorithms Laboratory /************************ OUTPUT ************************* Enter the no. of vertices Enter the adjacency matrix 0101 0010 0000 0010 The transitive closure is 0 1 1 1 0 0 1 0 0 0 0 0 0 0 1 0 : :4 :

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

58

Lab Manual: Algorithms Laboratory XV. Implement N Queens 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 i1 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 endif repeat 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; k1 //k is current row X(k) current column While k>0 do //for all rows do X(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 repeat if X(k)<=n //a possible is found then if k=n //is a solution complete then print(x) //if yes ,print the array else kk+1 X(k)0//go to the new row endif else kk-1 //backtrack endif repeat

59

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))

60

Lab Manual: Algorithms Laboratory c[r]++; 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

Lab Manual: Algorithms Laboratory

/*************************** OUTPUT ************************** Enter the number of Queens 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 - :4

62

Lab Manual: Algorithms Laboratory *************************************************************/

63