Daa Lab Manual Cse
Daa Lab Manual Cse
Daa Lab Manual Cse
Analysis of Algorithm
Lab Manual
(CSE-VI-SEM)
1
S.No Name of the program
Print all the nodes reachable from a given starting node in a digraph using
1 BFS method and Check
whether a given graph is connected or not using DFS method.
Sort a given set of elements and determine the time required to sort the
elements using following
2 algorithms:
Merge Sort
Quick Sort
2
Program 1: Print all the nodes reachable from a given starting node in a digraph using BFS
method and Check whether a given graph is connected or not using DFS method.
1. Print all the nodes reachable from a given starting node in a digraph using BFS method.
Breadth First Search (BFS) algorithm traverses a graph in a breadth ward motion and uses a queue to
remember to get the next vertex to start a search.
1. Visit the adjacent unvisited vertex. Mark it as visited. Display it. Insert it in a queue.
2. If no adjacent vertex is found, remove the first vertex from the queue.
3. Repeat Rule 1 and Rule 2 until the queue is empty.
SOURCE CODE:
#include<stdio.h>
#include<conio.h>
int a[20][20],q[20],visited[20],n,i,j,f=-1,r=0;
void bfs(int v)
{
q[++r]=v;
3
visited[v]=1;
while(f<=r)
{
for(i=1;i<=n;i++)
if(a[v][i] && !visited[i])
{
visited[i]=1;
q[++r]=i;
}
f++;
v=q[f];
}
}
void main()
{
int v;
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",q[i]);
else printf("\n Bfs is not possible");
}
4
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;
printf("\n Enter number of vertices:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
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");
}
5
INPUT/ OUTPUT
6
Program 2: Sort a given set of elements and determine the time required to sort the
elements using following
algorithms:
Merge Sort
Quick Sort
Merge Sort
#include<stdio.h>
#include<time.h>
int b[50000];
void Merge(int a[], int low, int mid, int high)
{
int i, j, k;
i=low;
j=mid+1;
k=low;
while ( i<=mid && j<=high )
{
if( a[i] <= a[j] )
b[k++] = a[i++] ;
else
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];
}
voidMergeSort(int a[], int low, int high)
{
int mid;
if(low >= high)
return;
7
mid = (low+high)/2 ;
MergeSort(a, low, mid);
MergeSort(a, mid+1, high);
Merge(a, low, mid, high);
}
void main()
{
int n, a[50000],k;
clock_tst,et;
double ts;
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);
}
8
Quick Sort
#include <stdio.h>
#include <time.h>
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_tst,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++)
{
9
a[k]=rand();
printf("%d\t",a[k]);
}
st=clock();
QuickSort(a, 1, n);
et=clock();
ts=(double)(et-st)/CLOCKS _PER_SEC;
printf("\nSorted Numbers are: \n ");
for(k=1; k<=n; k++)
printf("%d\t", a[k]);
printf("\nThe time taken is %e",ts);
}
10
Program3: Implement Knapsack problem using
Dynamic Programming
#include<stdio.h>
int w[10],p[10],v[10][10],n,i,j,cap,x[10]={0};
int max(inti,int j){
return ((i>j)?i:j);
} int knap(inti,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]);
} int
main() {
int profit,count=0;
printf("\nEnter the number of objects ");
scanf("%d",&n);
printf("Enter the profit and weights of the elements \n "); for(i=1;i<=n;i++) {
printf("\nEnter profit and weight For object no %d :",i);
scanf("%d%d",&p[i],&w[i]);
}
printf("\nEnter the capacity ");
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);
11
i=n;
j=cap;
while(j!=0&&i!=0) {
if(v[i][j]!=v[i-1][j]) {
x[i]=1;
j=j-w[i];
i--;
}
else
i--;
}
printf("object 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);
}
12
Program 4: Find Minimum Cost Spanning Tree of a given undirected graph using
Kruskal's algorithm
Prim’s algorithm
#include<stdio.h>
#include<stdlib.h>
inti,j,k,a,b,u,v,n,ne=1;
intmin,mincost=0,cost[9][9],parent[9];
int find(int);
intuni(int,int);
void main() {
printf("\n Implementation 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;
}
}
}
u=find(u);
v=find(v); if(uni(u,v))
{
printf("\n%d edge (%d,%d) =%d\n",ne++,a,b,min);
mincost +=min;
13
}
cost[a][b]=cost[b][a]=999;
}
printf("\n\tMinimum cost = %d\n",mincost);
} int find(int
i) {
while(parent[i])
i=parent[i];
return i;
} int uni(inti,int j){ if(i!=j)
{ parent[j]=i; return 1;
}
return 0;
}
14
Program 5: From a given vertex in a weighted connected graph, find shortest paths to other
vertices using Dijkstra's algorithm
#include<stdio.h>
#define infinity 999
void dij(int n, int v,int cost[20][20], int dist[]) {
int i,u,count,w,flag[20],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];
}
} int
main() {
int n,v,i,j,cost[20][20],dist[20];
printf("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;
}
15
printf("\n enter the source matrix:");
scanf("%d",&v);
dij(n,v,cost,dist); printf("\n
shortest path : \n");
for(i=1;i<=n;i++)
if(i!=v)
printf("%d->%d,cost=%d\n",v,i,dist[i]);
}
16
Program 6: Implement Travelling Salesperson Problem using Dynamic Programming
#include<stdio.h>
int s,c[100][100],ver;
float optimum=999,sum;
/* function to swap array elements
*/ void swap(int v[], int i, int j) {
int t; t = v[i]; v[i] = v[j]; v[j] = t;
}
/* recursive function to generate permutations */
voidbrute_force(int v[], int n, int i) {
// this function generates the permutations of the array from element i to element n-1 int
j,sum1,k;
//if we are at the end of the array, we have one permutation
if (i == n) {
if(v[0]==s)
{
for (j=0; j<n; j++)
printf ("%d ", v[j]);
sum1=0;
for( k=0;k<n-1;k++) {
sum1=sum1+c[v[k]][v[k+1]];
}
sum1=sum1+c[v[n-1]][s];
printf("sum = %d\n",sum1);
if (sum1<optimum)
optimum=sum1;
}
}
else
// recursively explore the permutations starting at index i going through index n-1*/
for (j=i; j<n; j++) { /* try the array with i and j switched */
swap (v, i, j);
brute_force (v, n, i+1);
/* swap them back the way they were */ swap (v, i, j);
}
}
17
void nearest_neighbour(intver)
{ int min,p,i,j,vis[20],from;
for(i=1;i<=ver;i++)
vis[i]=0;
vis[s]=1; from=s;
sum=0;
for(j=1;j<ver;j++) {
min=999;
for(i=1;i<=ver;i++) if(vis[i] !=1 &&c[from][i]<min
&& c[from][i] !=0 ) { min= c[from][i];
p=i;
}
vis[p]=1;
from=p;
sum=sum+min;
}
sum=sum+c[from][s];
}
void main () { int
ver,v[100],i,j;
printf("Enter n : ");
scanf("%d",&ver);
for (i=0; i<ver; i++)
v[i] = i+1;
printf("Enter cost matrix\n");
for(i=1;i<=ver;i++)
for(j=1;j<=ver;j++)
scanf("%d",&c[i][j]);
printf("\nEnter source : ");
scanf("%d",&s); brute_force (v, ver, 0);
printf("\nOptimum solution with brute force technique is=%f\n",optimum);
nearest_neighbour(ver);
printf("\nSolution with nearest neighbour technique is=%f\n",sum);
printf("The approximation val is=%f",((sum/optimum)-1)*100);
printf(" % ");
}
18
19
Program 7: Implement All-Pairs Shortest Paths Problem using Floyd's algorithm
#include<stdio.h>
int min(int,int);
void floyds(int p[10][10],int n) {
inti,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);
}
main()
{
int p[10][10],w,n,e,u,v,i,j;
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++){
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++) {
20
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]);
}
}
21
Program 8 : Implement the following using Back Tracking
N Queen's problem
#include<stdio.h>
#include<math.h>
int a[30],count=0;
int place(intpos) { int
i; 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) {
inti,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;
}
}
else
k--;
}
}
void main() {
inti,n;
printf("Enter the number of
Queens\n"); scanf("%d",&n);
queen(n);
22
printf("\nTotal solutions=%d",count);
}
Hamiltonian Cycle
#include<iostream>
#define NODE 4
using namespace std;
int graph[NODE][NODE];
int path[NODE];
for (int i = 0; i < k; i++) //if vertex is already taken, skip that
if (path[i] == v)
return false;
return true;
}
bool cycleFound(int k) {
if (k == NODE) { //when all vertices are in the path
if (graph[path[k-1]][ path[0] ] == 1 )
return true;
23
else
return false;
}
for (int v = 1; v < NODE; v++) { //for all vertices except starting point
if (isValid(v,k)) { //if possible to add v in the path
path[k] = v;
if (cycleFound (k+1) == true)
return true;
path[k] = -1; //when k vertex will not in the solution
}
}
return false;
}
bool hamiltonianCycle() {
for (int i = 0; i < NODE; i++)
path[i] = -1;
path[0] = 0; //first vertex as 0
if ( cycleFound(1) == false ) {
cout << "Solution does not exist"<<endl;
return false;
}
displayCycle();
return true;
}
int main() {
int i,j;
cout << "Enter the Graph : " << endl;
for (i=0;i<NODE;i++){
for (j=0;j<NODE;j++){
cout << "Graph G(" << (i+1) << "," << (j+1) << ") = ";
cin >> graph[i][j];
}
}
cout << endl;
cout << "The Graph :" << endl;
for (i=0;i<NODE;i++){
for (j=0;j<NODE;j++){
cout << graph [i][j] << "\t";
}
cout << endl;
}
hamiltonianCycle();
}
24
Output:
Graph Coloring
#include<stdio.h>
#include<conio.h>
static int m, n;
static int c=0;
static int count=0;
int g[50][50];
int x[50];
void nextValue(int k);void GraphColoring(int k);
void main()
{
int i, j;
int temp;
clrscr();
printf("\nEnter the number of nodes: " );
scanf("%d", &n);
/*
printf("\nIf edge exists then enter 1 else enter 0 \n");
for(i=1; i<=n; i++)
{
x[i]=0;
if(i==j)
25
g[i][j]=0;
else
scanf("%d", &temp);
g[i][j]=g[j][i]=temp;
*/
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d", &g[i][j]);
for(m=1;m<=n;m++)
if(c==1)
break;
26
}
GraphColoring(1);
//in for loop, m gets incremented first and then the condition is checked
//so it is m minus 1
void GraphColoring(int k)
int i;
while(1)
nextValue(k);
if(x[k]==0)
return;
if(k==n)
{
c=1;
for(i=1;i<=n;i++)
{
printf("%d ", x[i]);
27
count++;
printf("\n");
else
GraphColoring(k+1);
}
void nextValue(int k)
int j;
while(1)
x[k]=(x[k]+1)%(m+1);
if(x[k]==0)
return;
for(j=1;j<=n;j++)
if(g[k][j]==1&&x[k]==x[j])
break;
if(j==(n+1))
return;
28
}
OUTPUT:
Enter the number of nodes: 5
0 1 0 1 1
1 0 1 1 0
0 1 0 1 1
1 1 1 0 1
1 0 1 1 0
1 2 1 3 2
1 3 1 2 3
2 1 2 3 1
2 3 2 1 3
3 1 3 2 1
3 2 3 1 2
29