0% found this document useful (0 votes)
88 views45 pages

Krishna DAA

The program implements Dijkstra's algorithm to find the shortest path between a starting node and other nodes in a graph. It takes as input an adjacency matrix representing the graph and starts by initializing various arrays like distance, predecessor etc. It then iteratively finds the unvisited node with the minimum distance and updates the distance and predecessor arrays until all nodes are visited. The output contains the shortest path from the starting node to all other nodes in the graph.

Uploaded by

Anshika Mann
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
88 views45 pages

Krishna DAA

The program implements Dijkstra's algorithm to find the shortest path between a starting node and other nodes in a graph. It takes as input an adjacency matrix representing the graph and starts by initializing various arrays like distance, predecessor etc. It then iteratively finds the unvisited node with the minimum distance and updates the distance and predecessor arrays until all nodes are visited. The output contains the shortest path from the starting node to all other nodes in the graph.

Uploaded by

Anshika Mann
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

[Type here]

GATEWAY INSTITUTE OF ENGINEERING


AND TECHNOLOGY

PRACTICAL FILE

DESIGN AND ANALYSIS OF ALGORITHMS LAB

SUBMITTED TO : MS. SHEETAL GARG


SUBMITTED BY : KRISHNA PRATAP
SINGH CHAUHAN
[Type here]

Index

S.no Practical
1. Sort a given set of elements using the Quick 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. The elements can be read from a file or can be generated using the random
number generator.
2. Implement a parallelized Merge Sort algorithm to sort a given set of elements 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. The elements can be read from a file or can be generated using
the random number generator.
3. (A) Write a program to obtain the Topological ordering of vertices in a given digraph.
(B) Write a program to compute the transitive closure of a given DG using Warshall’s
Algorithm .

4. Write a program to implement 0/1 knapsack problem using dynamic programming


5. Write a program to find the shortest path of other vertices using Djikstra’s algorithm
6. Write a program to find MST of given undirected graph using Kruskal’s algorithm .
7. (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 or not using DFS method.
8. Find a subset of a given set S = {sl,s2,....,sn} of n positive integers whose sum isequal 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 solution.
9. Implement any scheme to find the optimal solution for the Traveling Salesperson problem
and then solve the same problem instance using any approximation algorithm and
determine the error in the approximation
10. Find Minimum Cost Spanning Tree of a given undirected graph using Prim‟s algorithm.
11. Implement All-Pairs Shortest Paths Problem using Floyds algorithm. Parallelize this
algorithm, implement it using Open and determine the speed-up achieved.
12. Implement N Queens problem using Back Tracking.
[Type here]

Practical -1
Question . Write a program to sort a given set of elements
using the Quicksort method.

// C Program to Perform Quick Sort //


#include <stdio.h>
void quicksort(int[], int, int);
int main()
{
int list[50];
int size, i;
printf("Enter the number of elements: ");
scanf("%d", &size);
printf("Enter the elements to be sorted:\n");
for (i = 0; i < size; i++)
{
scanf("%d", &list[i]);
}
quicksort(list, 0, size - 1);
printf("After applying quick sort\n");
for (i = 0; i < size; i++)
{
printf("%d ", list[i]);
}
printf("\n");
return 0;
}
[Type here]

void quicksort(int list[], int low, int high)


{
int pivot, i, j, temp;
if (low < high)
{
pivot = low;
i = low;
j = high;
while (i < j)
{
while (list[i] <= list[pivot] && i <= high)
{
i++;
}
while (list[j] > list[pivot] && j >= low)
{
j--;
}
if (i < j)
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
temp = list[j];
list[j] = list[pivot];
list[pivot] = temp;
[Type here]

quicksort(list, low, j - 1);


quicksort(list, j + 1, high);
}
}

OUTPUT
[Type here]

Practical-2
Q2. Write a program to Implement a parallelized Merge Sort
algorithm to sort a given set of element .

#include <stdio.h>
#define max 10
int a[11] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0 };
int b[10];
void merging(int low, int mid, int high) {
int l1, l2, i;
for (l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++)
{
if (a[l1] <= a[l2])
b[i] = a[l1++];
else
b[i] = a[l2++];
}
while (l1 <= mid)
b[i++] = a[l1++];
while (l2 <= high)
b[i++] = a[l2++];
for (i = low; i <= high; i++)
a[i] = b[i];
}
void sort(int low, int high)
{
int mid;
[Type here]

if (low < high)


{
mid = (low + high) / 2;
sort(low, mid);
sort(mid + 1, high);
merging(low, mid, high);
}
else {
return;
}
}
int main() {
int i;
printf("List before sorting\n");
for (i = 0; i <= max; i++)
printf("%d ", a[i]);
sort(0, max);
printf("\nList after sorting\n");
for (i = 0; i <= max; i++)
printf("%d ", a[i]);
}

OUTPUT
[Type here]

Practical -3
Question. (A) Write a program to obtain the Topological
ordering of vertices in a given digraph .

#include <stdio.h>
int main(){
int i,j,k,n,a[10][10],indeg[10],flag[10],count=0;
printf("Enter the no of vertices:\n");
scanf("%d",&n);
printf("Enter the adjacency matrix:\n");
for(i=0;i<n;i++){
printf("Enter row %d\n",i+1);
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
for(i=0;i<n;i++){
indeg[i]=0;
flag[i]=0;
}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
indeg[i]=indeg[i]+a[j][i];
printf("\nThe topological order is:");
while(count<n){
for(k=0;k<n;k++){
if((indeg[k]==0) && (flag[k]==0)){
printf("%d ",(k+1));
[Type here]

flag [k]=1;
}
for(i=0;i<n;i++){
if(a[i][k]==1)
indeg[k]--;
}
}
count++;
}
return 0;
}

OUTPUT
[Type here]

Practical -3
Question.(B) Write a program to compute the transitive
closure of a given DG using Warshall’s Algorithm .

#include<stdio.h>
#include<conio.h>
#include<math.h>
int max(int,int);
void warshal(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++)
p[i][j]=max(p[i][j],p[i][k]&&p[k][j]);
}
int max(int a,int b) {
;
if(a>b)
return(a); else
return(b);
}
void main() {
int p[10][10]= {0},n,e,u,v,i,j;
clrscr();
printf("\n Enter the number of vertices:");
scanf("%d",&n);
printf("\n Enter the number of edges:");
[Type here]

scanf("%d",&e);
for (i=1;i<=e;i++) {
printf("\n Enter the end vertices of edge %d:",i);
scanf("%d%d",&u,&v);
p[u][v]=1;
}
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");
}
warshal(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");
}
getch();
}
[Type here]

OUTPUT
[Type here]

Practical-4
Question. Write a program to implement 0/1 knapsack problem
using dynamic programming .

#include<stdio.h>
int max(int a, int b) { return (a > b)? a : b; }
int knapSack(int W, int wt[], int val[], int n)
{
int i, w;
int K[n+1][W+1];
for (i = 0; i <= n; i++)
{
for (w = 0; w <= W; w++)
{
if (i==0 || w==0)
K[i][w] = 0;
else if (wt[i-1] <= w)
K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]);
else
K[i][w] = K[i-1][w];
}
}
return K[n][W];
}
int main()
{
int i, n, val[20], wt[20], W;
printf("Enter number of items:");
[Type here]

scanf("%d", &n);
printf("Enter value and weight of items:\n");
for(i = 0;i < n; ++i){
scanf("%d%d", &val[i], &wt[i]);
}
printf("Enter size of knapsack:");
scanf("%d", &W);
printf("%d", knapSack(W, wt, val, n));
return 0;
}

OUTPUT
[Type here]

Practical-5

Question. Write a program to find the shortest path of other


vertices using Djikstra’s algorithm .

#include<stdio.h>
#include<conio.h>
#define INFINITY 9999
#define MAX 10
void dijikstra(int G[MAX][MAX], int n, int startnode);
void main() {
int G[MAX][MAX], i, j, n, u;
clrscr();
printf("\nEnter the no. of vertices:: ");
scanf("%d", &n);
printf("\nEnter the adjacency matrix::\n");
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
scanf("%d", &G[i][j]);
printf("\nEnter the starting node:: ");
scanf("%d", &u);
dijikstra(G, n, u);
getch();
}
void dijikstra(int G[MAX][MAX], int n, int startnode)
{
int cost[MAX][MAX], distance[MAX], pred[MAX];
[Type here]

int visited[MAX], count, mindistance, nextnode, i, j;


for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
if (G[i][j] == 0)
cost[i][j] = INFINITY;
else
cost[i][j] = G[i][j];
for (i = 0; i < n; i++)
{
distance[i] = cost[startnode][i];
pred[i] = startnode;
visited[i] = 0;
}
distance[startnode] = 0;
visited[startnode] = 1;
count = 1;
while (count < n - 1) {
mindistance = INFINITY;
for (i = 0; i < n; i++)
if (distance[i] < mindistance && !visited[i])
{
mindistance = distance[i];
nextnode = i;
}
visited[nextnode] = 1;
for (i = 0; i < n; i++)
if (!visited[i])
if (mindistance + cost[nextnode][i] < distance[i])
[Type here]

{
distance[i] = mindistance + cost[nextnode][i];
pred[i] = nextnode; }
}
count++;
}
for (i = 0; i < n; i++)
if (i != startnode)
{
printf("\nDistance of %d = %d", i, distance[i]);
printf("\nPath = %d", i);
j = i;
do
{
j = pred[j];
printf(" <-%d", j);
} while (j != startnode);
}
}
[Type here]

OUTPUT
[Type here]

Practical -6

Q6. Write a program to find MST of given undirected graph using


Kruskal’s algorithm .

#include<stdio.h>
#define MAX 30
typedef struct edge
{
int u, v, w;
}edge;
typedef struct edgelist
{
edge data[MAX];
int n;
}edgelist;
edgelist elist;
int G[MAX][MAX], n;
edgelist spanlist;
void kruskal();
int find(int belongs[], int vertexno);
void union1(int belongs[], int c1, int c2);
void sort();
void print();
void main()
{
int i, j, total_cost;
printf("\nEnter number of vertices:");
[Type here]

scanf("%d", &n);
printf("\nEnter the adjacency matrix:\n");
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
scanf("%d", &G[i][j]);
kruskal();
print();
}
void kruskal()
{
int belongs[MAX], i, j, cno1, cno2;
elist.n = 0;

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


for (j = 0; j < i; j++)
{
if (G[i][j] != 0)
{
elist.data[elist.n].u = i;
elist.data[elist.n].v = j;
elist.data[elist.n].w = G[i][j];
elist.n++;
}
}
sort();
for (i = 0; i < n; i++)
belongs[i] = i;
spanlist.n = 0;
[Type here]

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


{
cno1 = find(belongs, elist.data[i].u);
cno2 = find(belongs, elist.data[i].v);
if (cno1 != cno2)
{
spanlist.data[spanlist.n] = elist.data[i];
spanlist.n = spanlist.n + 1;
union1(belongs, cno1, cno2);
}
}
}
int find(int belongs[], int vertexno)
{
return(belongs[vertexno]);
}
void union1(int belongs[], int c1, int c2)
{
int i;
for (i = 0; i < n; i++)
if (belongs[i] == c2)
belongs[i] = c1;
}
void sort()
{
int i, j;
edge temp;
for (i = 1; i < elist.n; i++)
[Type here]

for (j = 0; j < elist.n - 1; j++)


if (elist.data[j].w > elist.data[j + 1].w)
{
temp = elist.data[j];
elist.data[j] = elist.data[j + 1];
elist.data[j + 1] = temp; }
}
void print()
{
int i, cost = 0;
for (i = 0; i < spanlist.n; i++)
{
printf("\n%d\t%d\t%d", spanlist.data[i].u, spanlist.data[i].v, spanlist.data[i].w);
cost = cost + spanlist.data[i].w;
}
printf("\n\nCost of the spanning tree=%d", cost);
}

OUTPUT
[Type here]

Practical-7
Question . (a)Print all the nodes reachable from a given
starting node in a digraph using BFS method.

#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++]);
}
}
void main()
{
int v;
//clrscr();
printf("\n Enter the number of vertices:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{ q[i]=
0;
[Type here]

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

OUTPUT
[Type here]

Practical-7
Question –(b)Check whether a given graph is connected or not
using DFS method.
#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++)
{
reach[i]=0;
[Type here]

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();
}
[Type here]

OUTPUT
[Type here]

Practical -8
Question - Find a subset of a given set S = {sl,s2,.. . .,sn} of n
positive integers whose sum isequal 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 solution.
#include<stdio.h>
#include<conio.h>
int s[10],d,n,set[10],count=0;
void display(int);
int flag = 0;
int subset(int sum,int i)
{
if(sum == d)
{
flag = 1;
display(count);
return;
}
if(sum>d || i>=n)return;
else
{
set[count]=s[i];
count++;
subset(sum+s[i],i+1);
count--;
[Type here]

subset(sum,i+1);
}
}
void main()
{

int i;
//clrscr();
printf("ENTER THE NUMBER OF THE ELEMENTS IN THE SET : ");
scanf("%d",&n);
printf("ENTER THE SET OF VALUES : ");
for(i=0;i<n;i++){
scanf("%d",&s[i]);;}

printf("ENTER THE SUM : ");


scanf("%d",&d);
printf("THE PROGRAM OUTPUT IS: ");
subset(0,0);
if(flag == 0)
printf("There is no solution");
getch();
}

void display(int count)


{
int i;
printf("\t{");
[Type here]

for(i=0;i<count;i++)
printf("%d,",set[i]);
printf("}");
}

OUTPUT
[Type here]

Practical -9
Question - Implement any scheme to find the optimal solution
for the Traveling Salesperson problem and then solve the same
problem instance using any approximation algorithm and
determine the error in the approximation.

#include<stdio.h>
int ary[10][10],completed[10],n,cost=0;
void takeInput()
{
int i,j;
printf("Enter the number of villages: ");
scanf("%d",&n);
printf("\nEnter the Cost Matrix\n");
for(i=0;i < n;i++)
{
printf("\nEnter Elements of Row: %d\n",i+1);
for( j=0;j < n;j++)
scanf("%d",&ary[i][j]);
completed[i]=0;
}
printf("\n\nThe cost list is:");
for( i=0;i < n;i++)
{ printf("\n");
for(j=0;j < n;j++)
printf("\t%d",ary[i][j]);
[Type here]

}
}
void mincost(int city)
{
int i,ncity;
completed[city]=1;
printf("%d--->",city+1);
ncity=least(city);
if(ncity==999)
{
ncity=0;
printf("%d",ncity+1);
cost+=ary[city][ncity];
return;
}

mincost(ncity);
}
int least(int c)
{
int i,nc=999;
int min=999,kmin;
for(i=0;i < n;i++)
{
if((ary[c][i]!=0)&&(completed[i]==0))
if(ary[c][i]+ary[i][c] < min)
{
min=ary[i][0]+ary[c][i];
[Type here]

kmin=ary[c][i];
nc=i;
}
}
if(min!=999)
cost+=kmin;

return nc;
}
int main()
{
takeInput();

printf("\n\nThe Path is:\n");


mincost(0); //passing 0 because starting vertex

printf("\n\nMinimum cost is %d\n ",cost);

return 0;
}
[Type here]

OUTPUT
[Type here]

Practical -10
Question . Find Minimum Cost Spanning Tree of a given
undirected graph using Prim‟s algorithm.
#include<stdio.h>
#include<stdlib.h>

#define infinity 9999


#define MAX 20

int G[MAX][MAX],spanning[MAX][MAX],n;

int prims();

int main()
{
int i,j,total_cost;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++) scanf("%d",&G[i]
[j]); total_cost=prims(); printf("\
nspanning tree matrix:\n");
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",spanning[i][j]);
}
printf("\n\nTotal cost of spanning tree=%d",total_cost);
return 0;
}

int prims()
{
int cost[MAX][MAX];
int u,v,min_distance,distance[MAX],from[MAX];
int visited[MAX],no_of_edges,i,min_cost,j;
//create cost[][] matrix,spanning[][]
for(i=0;i<n;i++)
for(j=0;j<n;j++)
[Type here]

{ if(G[i]
[j]==0)
cost[i][j]=infinity;
else cost[i]
[j]=G[i][j];
spanning[i][j]=0;
}
//initialise visited[],distance[] and from[]
distance[0]=0;
visited[0]=1;
for(i=1;i<n;i++)
{
distance[i]=cost[0][i];
from[i]=0;
visited[i]=0;
}
min_cost=0; //cost of spanning tree
no_of_edges=n-1; //no. of edges to be added
while(no_of_edges>0)
{
//find the vertex at minimum distance from the tree
min_distance=infinity;
for(i=1;i<n;i++)
if(visited[i]==0&&distance[i]<min_distance)
{
v=i;
min_distance=distance[i];
}
u=from[v];
//insert the edge in spanning tree
spanning[u][v]=distance[v];
spanning[v][u]=distance[v];
no_of_edges--;
visited[v]=1;
//updated the distance[] array
for(i=1;i<n;i++) if(visited[i]==0&&cost[i]
[v]<distance[i])
{
distance[i]=cost[i][v];
from[i]=v;
}
min_cost=min_cost+cost[u][v];
}
return(min_cost);
}
[Type here]

OUTPUT
[Type here]

Practical -11
Question .Implement All-Pairs Shortest Paths Problem using
Floyds algorithm. Parallelize this algorithm, implement it using
Open and determine the speed-up achieved.

#include<stdio.h>
#define V 4
#define INF 99999
void printSolution(int dist[][V]);
void floydWarshall (int graph[][V])
{
int dist[V][V], i, j, k;
for (i = 0; i < V; i++)
for (j = 0; j < V; j++)
dist[i][j] = graph[i][j];
for (k = 0; k < V; k++)
{
for (i = 0; i < V; i++)
{
for (j = 0; j < V; j++)
{
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
[Type here]

printSolution(dist);
}
void printSolution(int dist[][V])
{
printf ("The following matrix shows the shortest distances"
" between every pair of vertices \n");
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
if (dist[i][j] == INF)
printf("%7s", "INF");
else
printf ("%7d", dist[i][j]);
}
printf("\n");
}
}
int main()
{
int graph[V][V] = { {0, 5, INF, 10},
{INF, 0, 3, INF},
{INF, INF, 0, 1},
{INF, INF, INF, 0}
};

floydWarshall(graph);
[Type here]

return 0;
}

OUTPUT
[Type here]

Practical -12
Question . Implement N Queen&#39;s problem using Back
Tracking.

#include<stdio.h>
#include<math.h>
int board[20],count;
int main()
{
int n,i,j;
void queen(int row,int n);
printf(" - N Queens Problem Using Backtracking -");
printf("\n\nEnter number of Queens:");
scanf("%d",&n);
queen(1,n);
return 0;
}
void print(int n)
{
int i,j;
printf("\n\nSolution %d:\n\n",++count);
for(i=1;i<=n;++i)
printf("\t%d",i);
for(i=1;i<=n;++i)
{
printf("\n\n%d",i);
[Type here]

for(j=1;j<=n;++j)
{
if(board[i]==j)
printf("\tQ");
else
printf("\t-");
}
}
}

int place(int row,int column)


{
int i;
for(i=1;i<=row-1;++i)
{
//checking column and digonal conflicts
if(board[i]==column)
return 0;
else
if(abs(board[i]-column)==abs(i-row))
return 0;
}
return 1;
}

void queen(int row,int n)


{int column;
[Type here]

for(column=1;column<=n;++column)
{
if(place(row,column))
{
board[row]=column;
if(row==n)
print(n);
else
queen(row+1,n);
}
}
}
[Type here]

OUTPUT
[Type here]

You might also like