DAA Lab Manual
DAA Lab Manual
CSE
Prepared by: Approved & Reviewed by: Issued by: w.e.f Date:
Guru Nanak Institute of Technology
Dahegaon, Kalmeshwar Road, NAGPUR– 441501 (M.S.)
INDEX
2 Guidelines to Students 5
5 References 29
2
INTRODUCTION ABOUT LAB
There are 66 systems (Compaq Presario) installed in this Lab. Their configurations
are as follows:
Processor : Core 2 Duo
RAM : 1 GB
Hard Disk : 160 GB
Monitor : 17” TFT Color Monitor
Mouse : Optical Mouse
Key Board : Multimedia Keyboard
Network Interface card : Present
Software
1 All systems are configured in Single Boot mode .
2 Each student has a separate login for database access
3 Latest Technologies like DOT NET and J2EE are installed in some systems.
4 Software’ s installed: C, C++, JDK1.5, OFFICE-XP, J2EE.
5 Systems are provided for students in the 1:1 ratio.
6 Systems are assigned numbers and same system is allotted for students when
they do the lab.
3
4
LAB CODE:
1 Equipment in the lab for the use of student community. Students need to maintain a
proper decorum in the computer lab. Students must use the equipment with care.
Any damage is caused is punishable.
2 Students are required to carry their observation / programs book with completed
exercises while entering the lab.
3 Students are supposed to occupy the machines allotted to them and are not
supposed to talk or make noise in the lab. The allocation is put up on the lab notice
board.
4 Lab can be used in free time / lunch hours by the students who need to use the
systems should take prior permission from the lab in-charge.
5
6
LIST OF PRACTICALS
7
Practical -01
Sort a given set of elements using the Quicksort method and determine the time required
to sort the elements. Repeat the experiment for different values of n. The elements can
be read from a file or can be generated using the random number generator.
Theory:
1. The divide-and-conquer approach can be used to arrive at an efficient sorting
method different from merge sort.
2. In merge sort, the file a[1:n] was divided at its midpoint into sub arrays which were
independently sorted & later merged.
3. In Quick sort, the division into 2 sub arrays is made so that the sorted sub arrays do
not need to be merged later.
4. This is accomplished by rearranging the elements in a[1:n] such that a[I]<=a[j] for all I
between 1 & n and all j between (m+1) & n for some m, 1<=m<=n.
8. It is assumed that a[p]>=a[m] and that a[m] is the partitioning element. If m=1 &
p-1=n, then a[n+1] must be defined and must be greater than or equal to all elements
in a[1:n]
9. The assumption that a[m] is the partition element is merely for convenience, other
choices for the partitioning element than the first item in the set are better in
practice.
1. Algorithm Partition(a,m,p)
2. //within a[m],a[m+1],…..,a[p-1] the elements
3. // are rearranged in such a manner that if
4. //initially t=a[m],then after completion
5. //a[q]=t for some q between m and
6. //p-1,a[k]<=t for m<=k<q, and
7. //a[k]>=t for q<k<p. q is returned
8. //Set a[p]=infinite.
8
9. {
10. v=a[m];I=m;j=p;
11. repeat
12. {
13. repeat
14. I=I+1;
15. until(a[I]>=v);
16. repeat
17. j=j-1;
18. until(a[j]<=v);
19. if (I<j) then interchange(a,i.j);
20. }until(I>=j);
21. a[m]=a[j]; a[j]=v;
22. retun j;
23. }
1. Algorithm Interchange(a,I,j)
2. //Exchange a[I] with a[j]
3. {
4. p=a[I];
5. a[I]=a[j];
6. a[j]=p;
7. }
1. Algorithm Quicksort(p,q)
2. //Sort the elements a[p],….a[q] which resides
3. //is the global array a[1:n] into ascending
4. //order; a[n+1] is considered to be defined
5. // and must be >= all the elements in a[1:n]
6. {
7. if(p<q) then // If there are more than one element
8. {
9. // divide p into 2 subproblems
10. j=partition(a,p,q+1);
11. //’j’ is the position of the partitioning element.
12. //solve the subproblems.
13. quicksort(p,j-1);
14. quicksort(j+1,q);
15. //There is no need for combining solution.
16. }
17. }
# include <stdio.h>
# include <conio.h>
# include <time.h>
9
void Exch(int *p, int *q)
{
int temp = *p;
*p = *q;
*q = temp;
}
void QuickSort(int a[], int low, int high)
{
int i, j, key, k;
if(low>=high)
return;
key=low; i=low+1; j=high;
while(i<=j)
{
while ( a[i] <= a[key] ) i=i+1;
while ( a[j] > a[key] ) j=j-1;
if(i<j) Exch(&a[i], &a[j]);
}
Exch(&a[j], &a[key]);
QuickSort(a, low, j-1);
QuickSort(a, j+1, high);
}
void main()
{
int n, a[1000],k;
clock_t st,et;
double ts;
clrscr();
printf("\n Enter How many Numbers: ");
scanf("%d", &n);
printf("\nThe Random Numbers are:\n");
for(k=1; k<=n; k++)
{
a[k]=rand();
printf("%d\t",a[k]);
}
st=clock();
QuickSort(a, 1, n);
et=clock();
ts=(double)(et-st)/CLOCKS_PER_SEC;
10
printf("\nSorted Numbers are: \n ");
for(k=1; k<=n; k++)
printf("%d\t", a[k]);
printf("\nThe time taken is %e",ts);
getch();
}
11
2. Implement a Merge Sort algorithm to sort a given set of elements and determine the
time required to sort the elements. The elements can be read from a file or can be
generated using the random number generator.
Theory :
1. Algorithm MergeSort(low,high)
2. //a[low:high] is a global array to be sorted
3. //Small(P) is true if there is only one element
4. //to sort. In this case the list is already sorted.
5. {
6. if (low<high) then //if there are more than one element
7. {
8. //Divide P into subproblems
9. //find where to split the set
10. mid = [(low+high)/2];
11. //solve the subproblems.
12. mergesort (low,mid);
13. mergesort(mid+1,high);
14. //combine the solutions .
15. merge(low,mid,high);
16. }
17. }
1. Algorithm merge(low,mid,high)
2. //a[low:high] is a global array containing
3. //two sorted subsets in a[low:mid]
4. //and in a[mid+1:high].The goal is to merge these 2 sets into
5. //a single set residing in a[low:high].b[] is an auxiliary global array.
6. {
7. h=low; I=low; j=mid+1;
12
8. while ((h<=mid) and (j<=high)) do
9. {
10. if (a[h]<=a[j]) then
11. {
12. b[I]=a[h];
13. h = h+1;
14. }
15. else
16. {
17. b[I]= a[j];
18. j=j+1;
19. }
20. I=I+1;
21. }
22. if (h>mid) then
23. for k=j to high do
24. {
25. b[I]=a[k];
26. I=I+1;
27. }
28. else
29. for k=h to mid do
30. {
31. b[I]=a[k];
32. I=I+1;
33. }
34. for k=low to high do a[k] = b[k];
35.}
# include <stdio.h>
# include <conio.h>
#include<time.h>
void Merge(int a[], int low, int mid, int high)
{
int i, j, k, b[20];
i=low; j=mid+1; k=low;
while ( i<=mid && j<=high )
{
if( a[i] <= a[j] )
b[k++] = a[i++] ;
else
13
b[k++] = a[j++] ;
}
while (i<=mid) b[k++] = a[i++] ;
while (j<=high) b[k++] = a[j++] ;
for(k=low; k<=high; k++)
a[k] = b[k];
}
void MergeSort(int a[], int low, int high)
{
int mid;
if(low >= high)
return;
mid = (low+high)/2 ;
MergeSort(a, low, mid);
MergeSort(a, mid+1, high);
Merge(a, low, mid, high);
}
void main()
{
int n, a[2000],k;
clock_t st,et;
double ts;
clrscr();
printf("\n Enter How many Numbers:");
scanf("%d", &n);
printf("\nThe Random Numbers are:\n");
for(k=1; k<=n; k++)
{
a[k]=rand();
printf("%d\t", a[k]);
}
st=clock();
MergeSort(a, 1, n);
et=clock();
ts=(double)(et-st)/CLOCKS_PER_SEC;
printf("\n Sorted Numbers are : \n ");
for(k=1; k<=n; k++)
printf("%d\t", a[k]);
printf("\nThe time taken is %e",ts);
getch();
14
}
15
3. a. Obtain the Topological ordering of vertices in a given digraph.
Theory :
A topological sort of a DAG G is an ordering of the vertices of G such that for every
edge (ei, ej) of G we have i<j. That is, a topological sort is a linear ordering of all its vertices
such that if DAG G contains an edge (ei, ej), then ei appears before ej in the ordering. DAG
is cyclic then no linear ordering is possible.
In simple words, a topological ordering is an ordering such that any
directed path in DAG G traverses vertices in increasing order.
It is important to note that if the graph is not acyclic, then no linear
ordering is possible. That is, we must not have circularities in the directed
graph. For example, in order to get a job you need to have work experience,
but in order to get work experience you need to have a job.
Theorem:
#include<stdio.h>
#include<conio.h>
int a[10][10],n,indegre[10];
void find_indegre()
16
{ int j,i,sum;
for(j=0;j<n;j++)
{
sum=0;
for(i=0;i<n;i++)
sum+=a[i][j];
indegre[j]=sum;
}
}
void topology()
{
int i,u,v,t[10],s[10],top=-1,k=0;
find_indegre();
for(i=0;i<n;i++)
{
if(indegre[i]==0) s[++top]=i;
}
while(top!=-1)
{
u=s[top--];
t[k++]=u;
for(v=0;v<n;v++)
{
if(a[u][v]==1)
{
indegre[v]--;
if(indegre[v]==0) s[++top]=v;
}
}
}
printf("The topological Sequence is:\n");
for(i=0;i<n;i++)
printf("%d ",t[i]);
}
void main()
{
int i,j;
clrscr();
printf("Enter number of jobs:");
17
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
topology();
getch();
3. b. Compute the transitive closure of a given directed graph using Warshall's algorithm.
Theory :
Algorithm Warshall
Input: Adjacency matrix of relation on a set of elements
Output: Adjacency matrix of the transitive closure of .
Algorithm Body:
:= [initialize to ]
for := 1 to
for := 1 to
if , = 1 then
:= ∨ [form the Boolean OR of row and row , store it in ]
next
next
end Algorithm Warshall
# include <stdio.h>
# include <conio.h>
int n,a[10][10],p[10][10];
void path()
18
{
int i,j,k;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
p[i][j]=a[i][j];
for(k=0;k<n;k++)
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(p[i][k]==1&&p[k][j]==1) p[i][j]=1;
}
void main()
{
int i,j;
clrscr();
printf("Enter the number of nodes:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
path();
printf("\nThe path matrix is showm below\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("%d ",p[i][j]);
printf("\n");
}
getch();
}
19
4. Implement 0/1 Knapsack problem using Dynamic Programming.
Theory :
Algorithm :
for w = 0 to W
B[0,w] = 0
for i = 1 to n
B[i,0] = 0
for i = 1 to n
for w = 0 to W
if wi <= w // item i can be part of the solution
if bi + B[i-1,w-wi] > B[i-1,w]
B[i,w] = bi + B[i-1,w- wi]
else
B[i,w] = B[i-1,w]
else B[i,w] = B[i-1,w] // wi > w
#include<stdio.h>
#include<conio.h>
int w[10],p[10],v[10][10],n,i,j,cap,x[10]={0};
int max(int i,int j)
20
{
return ((i>j)?i:j);
}
int knap(int i,int j)
{
int value;
if(v[i][j]<0)
{
if(j<w[i])
value=knap(i-1,j);
else
value=max(knap(i-1,j),p[i]+knap(i-1,j-w[i]));
v[i][j]=value;
}
return(v[i][j]);
}
void main()
{
int profit,count=0;
clrscr();
printf("\nEnter the number of elements\n");
scanf("%d",&n);
printf("Enter the profit and weights of the elements\n");
for(i=1;i<=n;i++)
{
printf("For item no %d\n",i);
scanf("%d%d",&p[i],&w[i]);
}
printf("\nEnter the capacity \n");
scanf("%d",&cap);
for(i=0;i<=n;i++)
for(j=0;j<=cap;j++)
if((i==0)||(j==0))
v[i][j]=0;
else
v[i][j]=-1;
profit=knap(n,cap);
i=n;
j=cap;
while(j!=0&&i!=0)
21
{
if(v[i][j]!=v[i-1][j])
{
x[i]=1;
j=j-w[i];
i--;
}
else
i--;
}
printf("Items included are\n");
printf("Sl.no\tweight\tprofit\n");
for(i=1;i<=n;i++)
if(x[i])
printf("%d\t%d\t%d\n",++count,w[i],p[i]);
printf("Total profit = %d\n",profit);
getch();
}
22
5. From a given vertex in a weighted connected graph, find shortest paths to other
vertices using Dijkstra's algorithm.
Theory :
Algorithm :
Let the node at which we are starting be called the initial node. Let the distance of node
be the distance from the initial node to . Dijkstra's algorithm will assign some initial
distance values and will try to improve them step by step.
1. Assign to every node a tentative distance value: set it to zero for our initial node and
to infinity for all other nodes.
2. Mark all nodes unvisited. Set the initial node as current. Create a set of the unvisited
nodes called the consisting of all the nodes.
3. For the current node, consider all of its unvisited neighbors and calculate their
distances. Compare the newly calculated distance to the current
assigned value and assign the smaller one. For example, if the current node is
marked with a distance of 6, and the edge connecting it with a neighbor has length
2, then the distance to (through ) will be 6 + 2 = 8. If B was previously marked
with a distance greater than 8 then change it to 8. Otherwise, keep the current value.
4. When we are done considering all of the neighbors of the current node, mark the
current node as visited and remove it from the . A visited node will never
be checked again.
5. If the destination node has been marked visited (when planning a route between two
specific nodes) or if the smallest tentative distance among the nodes in the
is infinity (when planning a complete traversal; occurs when there is no
connection between the initial node and remaining unvisited nodes), then stop. The
algorithm has finished.
6. Select the unvisited node that is marked with the smallest tentative distance, and set
it as the new "current node" then go back to step 3.
#include<stdio.h>
#include<conio.h>
#define infinity 999
23
void dij(int n,int v,int cost[10][10],int dist[100])
{
int i,u,count,w,flag[10],min;
for(i=1;i<=n;i++)
flag[i]=0,dist[i]=cost[v][i];
count=2;
while(count<=n)
{
min=99;
for(w=1;w<=n;w++)
if(dist[w]<min && !flag[w])
min=dist[w],u=w;
flag[u]=1;
count++;
for(w=1;w<=n;w++)
if((dist[u]+cost[u][w]<dist[w]) && !flag[w])
dist[w]=dist[u]+cost[u][w];
}
}
void main( )
{
int n,v,i,j,cost[10][10],dist[10];
clrscr();
printf("\n Enter the number of nodes:");
scanf("%d",&n);
printf("\n Enter the cost matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=infinity;
}
printf("\n Enter the source matrix:");
scanf("%d",&v);
dij(n,v,cost,dist);
24
for(i=1;i<=n;i++)
if(i!=v)
printf("%d->%d,cost=%d\n",v,i,dist[i]);
getch();
}
25
6. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's
algorithm.
Theory :
In kruskal's algorithm the selection function chooses edges in increasing order of length
without worrying too much about their connection to previously chosen edges, except that
never to form a cycle. The result is a forest of trees that grows until all the trees in a forest
(all the components) merge in a single tree.
Algorithm kruskal(E,cost,n,t)
//E set of edges in G has ‘n’ vertices.
//cost[u,v] cost of edge (u,v).t set of edge in minimum cost spanning tree
// the first cost is returned.
{
for i=1 to n do parent[I]=-1;
I=0;mincost=0.0;
While((I<n-1)and (heap not empty)) do
{
j=find(n);
k=find(v);
if(j not equal k) than
{
i=i+1
t[i,1]=u;
t[i,2]=v;
mincost=mincost+cost[u,v];
union(j,k);
}
}
if(i notequal n-1) then write(“No spanning tree”)
else return minimum cost;
}
Analysis
3. The time complexity of minimum cost spanning tree algorithm in worst case is
O(|E|log|E|),
26
where E is the edge set of G.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int i,j,k,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
int find(int);
int uni(int,int);
void main()
{
clrscr();
printf("\n\n\tImplementation of Kruskal's algorithm\n\n");
printf("\nEnter the no. of vertices\n");
scanf("%d",&n);
printf("\nEnter the cost adjacency matrix\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
}
printf("\nThe edges of Minimum Cost Spanning Tree are\n\n");
while(ne<n)
{
for(i=1,min=999;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}}
}
27
u=find(u);
v=find(v);
if(uni(u,v))
{
printf("\n%d edge (%d,%d) =%d\n",ne++,a,b,min);
mincost +=min;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n\tMinimum cost = %d\n",mincost);
getch();
}
int find(int i)
{
while(parent[i])
I=parent[i];
return i;
}
int uni(int i, int j)
{
if(i!=j)
{
parent[j]=i;
return 1;
}
return 0;
}
28
7. Print all the nodes reachable from a given starting node in a digraph using BFS method.
Theory :
In Breadth first search we start at vertex v and mark it as having been reached. The
vertex v at this time is said to be unexplored. A vertex is said to have been explored by an
algorithm when the algorithm has visited all vertices adjacent from it. All unvisited vertices
adjacent from v are visited next. There are new unexplored vertices. Vertex v has now been
explored. The newly visited vertices have not been explored and are put onto the end of the
list of unexplored vertices. The first vertex on this list is the next to be explored. Exploration
continues until no unexplored vertex is left. The list of unexplored vertices acts as a queue
and can be represented using any of the standard queue representations.
ALGORITHM:
29
visited[w]=1
}
}
if q is empty then return;// No delete u from q;
} until (false)
}
for i= 1 to n do
visited[i] =0;
for i =1 to n do
if (visited[i]=0)then BFS(i)
}
here the time and space required by BFT on an n-vertex e-edge graph one O(n+e) and O(n)
resp if adjacency list is used.if adjancey matrix is used then the bounds are O(n2) and O(n)
resp
#include<stdio.h>
#include<conio.h>
int a[20][20],q[20],visited[20],n,i,j,f=0,r=-1;
void bfs(int v)
{
for(i=1;i<=n;i++)
if(a[v][i] && !visited[i])
q[++r]=i;
if(f<=r)
{
visited[q[f]]=1;
bfs(q[f++]);
}
}
30
void main()
{
int v;
clrscr();
printf("\n Enter the number of vertices:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
q[i]=0;
visited[i]=0;
}
printf("\n Enter graph data in matrix form:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
printf("\n Enter the starting vertex:");
scanf("%d",&v);
bfs(v);
printf("\n The node which are reachable are:\n");
for(i=1;i<=n;i++)
if(visited[i])
printf("%d\t",i); getch();
}
31
8. Check whether a given graph is connected or not using DFS method.
Theory :
A depth first search of a graph differs from a breadth first search in that the
exploration of a vertex v is suspended as soon as a new vertex is reached. At this time the
exploration of the new vertex u begins. When this new vertex has been explored, the
exploration of u continues. The search terminates when all reached vertices have been fully
explored. This search process is best-described recursively.
Algorithm DFS(v)
{
visited[v]=1
for each vertex w adjacent from v do
{
If (visited[w]=0)then
DFS(w);
}
}
#include<stdio.h>
#include<conio.h>
int a[20][20],reach[20],n;
void dfs(int v)
{
int i;
reach[v]=1;
for(i=1;i<=n;i++)
if(a[v][i] && !reach[i])
{
printf("\n %d->%d",v,i);
dfs(i);
}
}
void main()
{
int i,j,count=0;
clrscr();
printf("\n Enter number of vertices:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
32
reach[i]=0;
for(j=1;j<=n;j++)
a[i][j]=0;
}
printf("\n Enter the adjacency matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
dfs(1);
printf("\n");
for(i=1;i<=n;i++)
{
if(reach[i])
count++;
}
if(count==n)
printf("\n Graph is connected");
else
printf("\n Graph is not connected");
getch();
}
33
9. Implement any scheme to find the optimal solution for the Traveling Salesperson
problem.
Theory :
This technique is implemented in the traveling salesman problem [TSP] which are
asymmetric (Cij <>Cij) where this technique is an effective procedure.
[
For all rows do step 2
Find least cost in a column and negate it with rest of the elements.
: Preserve cost matrix C [which row reduced first and then column reduced]
for the i th time.
Calculate effective cost of the edges. (i, j)=least cost in the i th row excluding
(i, j) + least cost in the j th column excluding (i, j).
Compare all effective cost and pick up the largest l. If two or more have same
cost then arbitrarily choose any one among them.
Delete (i, j) means delete ith row and jth column change (j, i) value to infinity.
(Used to avoid infinite loop formation) If (i,j) not present, leave it.
Repeat step 1 to step 9 until the resultant cost matrix having order of 2*2 and
reduce it. (Both R.R and C.C)
34
Choose an edge [i, j] having value =0, at the first time for a preserved matrix
and leave that matrix.
#include<stdio.h>
#include<conio.h>
void main()
{
int n;/* Number of cities. */
int i,j,c[max][max];/* Loop counters. */
int tour[max];/* Cost matrix. */
cost;/* Least cost. */
clrscr();
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
scanf("%d",&c[i][j]);
if(c[i][j]==0)
c[i][j]=999;
}
35
for(i=0;i<n;i++)
tour[i]=i;
cost=tspdp(c,tour,0,n);
for(i=0;i<n;i++)
printf("%d - ",tour[i]+1);
printf("1\n");
getch();
/* Adjust positions. */
temp[start+1]=tour[i];
temp[i]=tour[start+1];
36
if(c[tour[start]][tour[i]]+(cost=tspdp(c,temp,start+1,n))<mincost)
{
mincost=c[tour[start]][tour[i]]+cost;
for(k=0;k<n;k++)
mintour[k]=temp[k];
}
}
37
10. Find Minimum Cost Spanning Tree of a given undirected graph using Prim’ s
algorithm.
Theory :
Start from an arbitrary vertex (root). At each stage, add a new branch (edge) to the
tree already constructed; the algorithm halts when all the vertices in the graph have been
reached.
Algorithm prims(e,cost,n,t)
{
Let (k, ) be an edge of minimum cost in E;
Mincost :=cost[k, ];
T[1,1]:=k; t[1,2]:= ;
For I:=1 to n do
If (cost[i, ]<cost[i,k]) then near[i]:= ;
Else near[i]:=k;
Near[k]:=near[l]:=0;
For i:=2 to n-1 do
{
Letj be an index such thatnear[j]≠0 and
Cost[j,near[j]] is minimum;
T[i,1]:=j; t[i,2]:=near[j];
Mincost:=mincost+ Cost[j,near[j]];
Near[j]:=0;
For k:=0 to n do
Ifnear((near[k]≠0) and (Cost[k,near[k]]>cost[k,j])) then
Near[k]:=j;
}
Return mincost;
}
4. The prims algorithm will start with a tree that includes only a minimum cost
edge of G.
38
5. Then, edges are added to the tree one by one. the next edge (i,j) to be added in
such that I is a vertex included in the tree, j is a vertex not yet included, and
cost of (i,j), cost[i,j] is minimum among all the edges.
#include<stdio.h>
#include<conio.h>
int a,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost=0,cost[10][10];
void main()
{
clrscr();
printf("\n Enter the number of nodes:");
scanf("%d",&n);
printf("\n Enter the adjacency matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
visited[1]=1;
printf("\n");
while(ne<n)
{
for(i=1,min=999;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]<min)
if(visited[i]!=0)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
if(visited[u]==0 || visited[v]==0)
{
printf("\n Edge %d:(%d %d) cost:%d",ne++,a,b,min);
mincost+=min;
visited[b]=1;
39
}
cost[a][b]=cost[b][a]=999;
}
printf("\n Minimun cost=%d",mincost);
getch();
}
40
11. Implement All-Pairs Shortest Paths Problem using Floyd's algorithm.
Theory :
Let G=<N,A> be a directed graph ’ N’ is a set of nodes and ‘ A’ is the set of edges.
We want to calculate the length of the shortest path between each pair of nodes.
The principle of optimality applies: if k is the node on the shortest path from i to j
then the part of the path from i to k and the part from k to j must also be optimal, that
is shorter.
Copy the above matrix-to-matrix D, which will give the direct distance between nodes.
We have to perform N iteration after iteration k.the matrix D will give you the distance
between nodes with only (1,2...,k)as intermediate nodes.
At the iteration k, we have to check for each pair of nodes (i,j) whether or not there
exists a path from i to j passing through node k.
ALGORITHM :
D=L
For 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 ]
41
Return D
ANALYSIS:
#include<stdio.h>
#include<conio.h>
int min(int,int);
void floyds(int p[10][10],int n)
{
int i,j,k;
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(i==j)
p[i][j]=0;
else
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);
}
void main()
{
int p[10][10],w,n,e,u,v,i,j;;
clrscr();
printf("\n Enter the number of vertices:");
scanf("%d",&n);
printf("\n Enter the number of edges:\n");
scanf("%d",&e);
for(i=1;i<=n;i++)
{
42
for(j=1;j<=n;j++)
p[i][j]=999;
}
for(i=1;i<=e;i++)
{
printf("\n Enter the end vertices of edge%d with its weight \n",i);
scanf("%d%d%d",&u,&v,&w);
p[u][v]=w;
}
printf("\n Matrix of input data:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d \t",p[i][j]);
printf("\n");
}
floyds(p,n);
printf("\n Transitive closure:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d \t",p[i][j]);
printf("\n");
}
printf("\n The shortest paths are:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
if(i!=j)
printf("\n <%d,%d>=%d",i,j,p[i][j]);
}
getch();
}
43
12. Implement N Queen's problem using Back Tracking.
Theory :
The 8 queen problem is a case of more general set of problems namely “ n queen
problem” . The basic idea: How to place n queen on n by n board, so that they don’ t
attack
each other. As we can expect the complexity of solving the problem increases with n. We
will briefly introduce solution by backtracking.
First let’ s explain what is backtracking? The boar should be regarded as a set of
constraints and the solution is simply satisfying all constraints. For example: Q1 attacks
some positions, therefore Q2 has to comply with these constraints and take place, not
directly attacked by Q1. Placing Q3 is harder, since we have to satisfy constraints of Q1
and Q2. Going the same way we may reach point, where the constraints make the
placement of the next queen impossible. Therefore we need to relax the constraints and
find new solution. To do this we are going backwards and finding new admissible
solution. To keep everything in order we keep the simple rule: last placed, first displaced.
In other words if we place successfully queen on the ith column but cannot find solution
for (i+1)th queen, then going backwards we will try to find other admissible solution for
the ith queen first. This process is called backtrack
Let’ s discuss this with example. For the purpose of this handout we will find solution of 4
queen problem.
Algorithm:
- Start with one queen at the first column first row
- Continue with second queen from the second column first row
- Go up until find a permissible situation
- Continue with next queen
#include<stdio.h>
#include<conio.h>
#include<math.h>
int a[30],count=0;
int place(int pos)
{
int i;
44
for(i=1;i<pos;i++)
{
if((a[i]==a[pos])||((abs(a[i]-a[pos])==abs(i-pos))))
return 0;
}
return 1;
}
void print_sol(int n)
{
int i,j;
count++;
printf("\n\nSolution #%d:\n",count);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(a[i]==j)
printf("Q\t");
else
printf("*\t");
}
printf("\n");
}
}
void queen(int n)
{
int k=1;
a[k]=0;
while(k!=0)
{ a[k]=a[k]+1;
while((a[k]<=n)&&!place(k))
a[k]++;
if(a[k]<=n)
{
if(k==n)
print_sol(n);
else
{
k++;
a[k]=0;
45
}
}
else
k--;
}
}
void main()
{
int i,n;
clrscr();
printf("Enter the number of Queens\n");
scanf("%d",&n);
queen(n);
printf("\nTotal solutions=%d",count);
getch();
}
46