Analysis & Design of Algorithms Laboratory (BCSL404: Department of Artificial Intelligence & Machine Learning
Analysis & Design of Algorithms Laboratory (BCSL404: Department of Artificial Intelligence & Machine Learning
1. Design and implement C/C++ Program to find Minimum Cost Spanning Tree of
agiven connected undirected graph using Kruskal's algorithm.
#include<stdio.h>
int ne=1,min_cost=0;
void main()
{
int n,i,j,min,a,u,b,v,cost[20][20],parent[20];
printf("Enter the no. of vertices:");
scanf("%d",&n);
printf("\nEnter the costmatrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&cost[i][j]);
for(i=1;i<=n;i++)
parent[i]=0;
printf("\nThe edges of spanning treeare\n");
while(ne<n)
{
min=999;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
while(parent[u])
u=parent[u];
while(parent[v])
v=parent[v];
if(u!=v)
{
printf("Edge %d\t(%d->%d)=%d\n",ne++,a,b,min);
min_cost=min_cost+min;
parent[v]=u;
}
cost[a][b]=cost[a][b]=999;
}
printf("\nMinimum cost=%d\n",min_cost);
}
Output:
2. Design and implement C/C++ Program to find Minimum Cost Spanning Tree of
agiven connected undirected graph using Prim's algorithm.
#include<stdio.h>
int a,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost=0,cost[10][10];
void main()
{
Output:
3.a Design and implement C/C++ Program to solve All-Pairs Shortest Paths problem using
Floyd's algorithm.
#include <stdio.h>
#include<limits.h>
#define V 4
int main() {
int graph[V][V]={{0,INT_MAX,3, INT_MAX},
{2,0,INT_MAX,INT_MAX},
{INT_MAX,7, 0, 1},
{6,INT_MAX,INT_MAX,0}};
floydWarshall(graph);
return 0;
}
Output:
3.b Design and implement C/C++ Program to find the transitive closure using
Warshal'salgorithm.
# include<stdio.h>
int n,a[10][10],p[10][10];
void path()
{
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;
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");
}
}
Output:
4. Design and implement C/C++Program to find shortest paths from agiven vertex in a
weighted connected graph to other vertices using Dijkstra's algorithm.
#include<stdio.h>
void dij(int, int[20][20],int[20],int[20],int);
void main() {
int i,j,n,visited[20],source,cost[20][20],d[20];
printf("Enter no. of vertices: ");
scanf("%d",&n);
printf("Enter the cost adjacency matrix\n");
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
scanf("%d",&cost[i][j]);
}
}
printf("\nEnter the source node:");
scanf("%d", &source);
dij(source, cost, visited, d, n);
for (i = 1; i <= n; i++) {
if(i != source)
printf("\nShortest path from %d to %d is %d",source, i, d[i]);
}
}
void dij(int source,int cost[20][20],int visited[20],int d[20],int n){
int i, j, min, u, w;
for(i=1;i<=n;i++){
visited[i] = 0;
d[i] =cost[source][i];
}
visited[source]=1;
d[source]=0;
for(j=2;j<=n;j++){
min = 999;
for(i=1;i<=n;i++){
if (!visited[i]) {
if(d[i]<min){
min = d[i];
u =i;
}
}
}
visited[u]=1;
for(w =1; w<=n; w++) {
if(cost[u][w]!=999 && visited[w]==0){
if (d[w] > cost[u][w] + d[u])
d[w]=cost[u][w]+d[u];
}
}
}
}
Output:
5. Design and implement C/C++ Program to obtain the Topological ordering of vertices in
a given digraph.
#include<stdio.h>
void findindegree(int [10][10],int[10],int);
void topological(int,int [10][10]);
void main()
{
int a[10][10],i,j,n;
printf("Enter the number of nodes:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
printf("\nThe adjacency matirxis:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
topological(n,a);
}
void findindegree(int a[10][10],int indegree[10],int n)
{
int i,j,sum;
for(j=1;j<=n;j++)
{
sum=0;
for(i=1;i<=n;i++)
{
sum=sum+a[i][j];
}
indegree[j]=sum;
}
}
void topological(int n,int a[10][10])
{
int k,top,t[100],i,stack[20],u,v,indegree[20];
k=1;
top=-1;
findindegree(a,indegree,n);
for(i=1;i<=n;i++)
{
if(indegree[i]==0)
{
stack[++top]=i;
}
}
while(top!=-1)
{
u=stack[top--];
t[k++]=u;
for(v=1;v<=n;v++)
{
if(a[u][v]==1)
{
indegree[v]--;
if(indegree[v]==0)
{
stack[++top]=v;
}}
}}
printf("\nTopological sequence is\n");
for(i=1;i<=n;i++)
printf("%d\t",t[i]);
}
Output:
6. Design and implement C/C++ Program to solve 0/1 Knapsack problem using Dynamic
Programming method.
#include<stdio.h>
#define MAX 50
int p[MAX],w[MAX],n;
int knapsack(int,int);
int max(int,int);
void main()
{
int m,i,optsoln;
Output:
7. Design and implement C/C++ Program to solve discrete Knapsack and continuous
Knapsack problems using greedy approximation method.
#include<iostream>
#include <vector>
#include<algorithm>
using namespace std;
//Structuretorepresentanitem
struct Item {
int weight;
int value;
};
//Function to solve discrete knapsack using greedy approach
int discreteKnapsack(vector<Item>& items, int capacity) {
// Sort items based on their value per unit weight
sort(items.begin(),items.end(), [](const Item& a,const Item& b){
return (double)a.value / a.weight>(double)b.value / b.weight;
});
int totalValue=0;
int currentWeight=0;
// Fill the knapsack with items
for(const Item& item:items){
if(currentWeight+ item.weight <= capacity){
currentWeight += item.weight;
totalValue+= item.value;
}
}
return totalValue;
}
// Function to solve continuous knapsack using greedy approach
double continuousKnapsack(vector<Item>&items,int capacity){
// Sort items based on their value per unit weight
sort(items.begin(),items.end(),[](const Item&a, const Item& b){
return (double)a.value/a.weight>(double)b.value/b.weight;
});
double totalValue=0.0;
int currentWeight = 0;
//Fill the knapsack with items fractionally
for (const Item& item : items) {
if(currentWeight + item.weight<=capacity){
currentWeight += item.weight;
totalValue+= item.value;
}else {
int remainingCapacity= capacity - currentWeight;
totalValue+= (double)item.value/ item.weight * remainingCapacity;
break;
}}
return totalValue;
}
int main() {
vector<Item>items;
int n, capacity;
//Input number of items and capacity of knapsack
cout <<"Enter the number of items: ";
cin>>n;
cout<<"Enter the capacity of knapsack:";
cin >> capacity;
// Inputtheweightand valueofeachitem
cout<<"Enter the weight and value of each item:"<<endl;
for (int i = 0; i < n; i++) {
Item item;
cout <<"Item "<< i + 1 <<": ";
cin>>item.weight>>item.value;
items.push_back(item);
}
//Solvediscreteknapsackproblem
int discreteResult=discreteKnapsack(items,capacity);
cout<<"Maximum value for discreteknapsack: "<<discreteResult <<endl;
//Solvecontinuousknapsack problem
double continuousResult=continuousKnapsack(items, capacity);
cout<<"Maximum value for continuous knapsack:"<<continuousResult<<endl; return 0;
}
Output:
8. Design and implement C/C++Program to find a subset of a given setS={sl, s2, .......... ,sn}of
N positive integers whose sum is equal to agiven positive integerd.
#include<stdio.h>
void subset(int,int,int);
int x[10],w[10],d,count=0;
void main()
{
int i,n,sum=0;
return;
}
subset(0,0,sum);
if(count==0)
{
printf("No solution\n");
return;
}
}
void subset(int cs,int k,int r)
{
int i;
x[k]=1;
if(cs+w[k]==d)
{
printf("\n\nSubset %d\n",++count);
for(i=0;i<=k;i++)
if(x[i]==1)
printf("%d\t",w[i]);
}
else
if(cs+w[k]+w[k+1]<=d)
subset(cs+w[k],k+1,r-w[k]);
if(cs+r-w[k]>=d && cs+w[k]<=d)
{
x[k]=0;
subset(cs,k+1,r-w[k]);
}
}
Output:
9. Design and implement C/C++ Program to sort a given set of n integer elements using
Selection Sort method and compute its time complexity. Run the program for varied values
of n> 5000 and record the time taken to sort. 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.
#include <stdio.h>
#include<stdlib.h>
#include <time.h>
//Function to perform selection sort
void selectionSort(int arr[], int n) {
int i, j, minIndex, temp;
for(i = 0; i < n-1; i++){
minIndex=i;
for(j = i +1; j <n; j++) {
if(arr[j]<arr[minIndex]){
minIndex = j;
}
}
//Swapthefoundminimumelementwiththefirstelement
temp = arr[minIndex];
arr[minIndex]=arr[i];
arr[i] = temp;
}
}
//Functiontogeneraterandomnumbersbetween 0 and 999
int generateRandomNumber() {
return rand() % 1000;
}
int main() {
//Setnvalue
int n =6000;
//Recordthestarttime
clock_t start= clock();
//Performselectionsort
selectionSort(arr, n);
//Recordtheendtime
clock_t end= clock();
//Calculatethetimetakenfor sorting
double time_taken=((double)(end-start)) / CLOCKS_PER_SEC;
//Output the time taken to sort for the current value of n
printf("\nTime taken tosort forn=%d: %lfseconds\n\n", n, time_taken);
// Displaysorted numbers
printf("Sorted numbers for n=%d:\n",n); for
(int i = 0; i < n; i++) {
printf("%d",arr[i]);
}
printf("\n\n");
//Free the dynamically allocated memory
free(arr);
return 0;
}
Output:
10. Design and implement C/C++ Program to sort a given set of n integer elements using
Quick Sort method and compute its time complexity. Run the program for varied values of
n> 5000 and record the time taken to sort. 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.
#include <stdio.h>
#include<stdlib.h>
#include <time.h>
//Functiontoswaptwoelements
void swap(int* a, int* b) {
int temp =*a;
*a= *b;
*b =temp;
}
//Functiontopartitionthearrayandreturnthepivotindex
int partition(int arr[], int low, int high) {
int pivot=arr[high];
int i = (low - 1);
for(int j=low;j<=high-1;j++){
if (arr[j] < pivot) {
i++;
swap(&arr[i],&arr[j]);
}
}
swap(&arr[i+1],&arr[high]);
return (i + 1);
}
//FunctiontoperformQuickSort
void quickSort(int arr[],int low,int high){
if (low < high) {
int pi=partition(arr,low,high);
int main() {
//Set nvalue
int n =6000;
//Generaterandomelementsforthearray
srand(time(NULL));
printf("Random numbers for n=%d:\n",n);
for (int i = 0; i < n; i++) {
arr[i]=generateRandomNumber();
printf("%d ", arr[i]);
}
printf("\n");
//Recordthestarttime
clock_t start= clock();
//Recordtheendtime
clock_t end=clock();
//Calculatethetimetakenfor sorting
double time_taken=((double)(end-start))/ CLOCKS_PER_SEC;
// Displaysorted numbers
printf("Sorted numbers for n=%d:\n",n); for
(int i = 0; i < n; i++)
{
printf("%d",arr[i]);
}
printf("\n\n");
return 0;
}
Output:
11. Design and implement C/C++ Program to sort a given set of n integer elements using
MergeSort method andcomputeits timecomplexity.Run theprogramforvaried values of n>
5000, and record the time taken to sort. 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.
#include <stdio.h>
#include<stdlib.h>
#include <time.h>
//Merge two subarraysof arr[]
//First subarray is arr[l..m]
//Second subarrayis arr[m+1..r]
void merge(int arr[],int l,int m,int r){
int i, j, k;
int n1=m-l+1;
int n2 = r - m;
//Mergethetemporaryarraysbackinto arr[l..r]
i=0;//Initial indexof firstsubarray
j=0;//Initial index ofsecondsubarray
k=l;//Initial indexofmergedsubarray
while (i < n1 && j < n2) {
if(L[i] <=R[j]) {
arr[k]=L[i];
i++;
}else {
arr[k]=R[j];
j++;
}
k++;
}
//CopytheremainingelementsofL[],ifthereareany
while (i < n1) {
arr[k]=L[i];
i++;
k++;
}
//Mergesort function
void mergeSort(int arr[],int l,int r){
if (l < r) {
//Sameas(l+r)/2,but avoids overflow for large l and r
int m = l + (r - l) / 2;
//Mergethesortedhalves
merge(arr, l, m, r);
}
}
//Functiontogeneraterandomnumbersbetween0and999
int generateRandomNumber() {
return rand()% 1000;
}
int main() {
//Setnvalue
int n = 6000;
//Generaterandomelementsforthearray
srand(time(NULL));
printf("Random numbers for n=%d:\n",n);
for (int i = 0; i < n; i++) {
arr[i]=generateRandomNumber();
printf("%d ", arr[i]);
}
printf("\n");
//Recordthestarttime
Output:
12. Design and implement C/C++ Program for N Queen's problem using Backtracking.
#include <iostream>
#include <vector>
using namespace std;
return true;
}
// If the queen cannot be placed in any column of this row, return false
return false;
}
// Function to solve the 4 Queens problem
void solve4Queens() {
int n = 4;
vector<vector<char>> board(n, vector<char>(n, '-'));
// Driver function
int main() {
cout << "Solution for 4 Queens problem:" << endl;
solve4Queens();
return 0;
}
Output:
VIVAQUESTIONS
1. What is an Algorithm?
Algorithm is a Step by step procedure to Solve a given problem for a finite number of input
producing finite number of output with desired output.
2. What is a Flow Chart?
Flow chart is a Graphical Representation of a solution to the Problem.
3. What is the difference between Algorithm,FlowChart,Program?
Algorithm specifies the different things to be followed for solving a Problem.
FlowChart is a Graphical Representation of a Solution to the Problem.Both
Algorithm and Flow Chartare Machine Independent.
Program is a Set of Instructions which is used a satool to communicate to the machine
to get our workdone,Program is Machine Dependent for particular Machine.
4. What is the Aim of DAA labor why we need to study DAA Lab
DAA is a discipline, where we are dealing with designing or writing the algorithm
keeping in Consideration of Space and Time Complexity, Such that Our Algorithm
should execute in a very minimum amount of time by Minimum Space or RAM.
5. Define Space and Time Complexity?Among this which one is more prioritized?
Space Complexeity is a measure of Amount of Space taken by a Program to finish its
Execution.
Time Complexeity is a measure of amount of time taken by a program to complte its
Execution.DependingUpon Application it is considered,EX:For Mobile or Handheld
Devices,We give Prefernce for both Spaceand time.
For a Huge and Inter active Systems like Web Applications we give more Preferences to
time Complexeity.
6. What is Design and what is Analysis of a Program?
Design is a Process of Writing an algorithm to a given Problem so that it should accept
finite number of input and finite number of output with a definite output and Should Exit
appropriately.
Analysis:Analysis is a next Phase of Writing an Algorithm ,in this phase we calculate
the Efficiency of an Algorithm i.e time and space needed by an algorithm.
27. Differentiate between Prims and Kruskals Algorithm for finding MST.
In Prims We consider any one vertex in the graph as Source and We compute the
distance from that source to other vertices ,after computing the vertices which has
minimum value among (n-1) vertices is added to tree vertices and that respective edges
added to tree Edges Set.The above mentioned Process continues till we reach (n-1)
vertices.
In Kruskals we first arrange the edges in Ascending Order and then we start to form the
tree which wont formcycles,if adding that edges forms cycles then that edges is dropped
fromadding to tree edges.The above saidprocess is continues till we reach the count of
(n-1)Vertices.
(ii) Verification(DeterministicStage)VerifyingThecorrectnessofNNumberof
Candidate Outputs.
53. What is NP-Complete Problems?
Np_Complete Problems belongs to Decision problems and NP type Problems .
These problems can be find the solutions byconverting or reducing to the problem
which we know theSolutions.
56. ExplainSubsetProblem.
In a given Set S ,find the Subset,in which the sum of all subset elements is equal tothe
sum d which is predefined in a problem.
57. ExplainN-QueensProblem.(
N-Queens Problem is of Placing a N-Queens in a N*N Chess board such that No 2-
Queens Should be placed in the same Row,Column and same diagnol(N=Should
consider both principal diagonal elements)
58. What is HamiltonianCircuit?(L2)
Hamiltonian circuit is a problem in which that circuit starts from a source vertex and
has other vertex in anyorder without repeatingandShould endwiththeSourcevertex
onlyi.e source and Destination vertexshould be same.
59. Explain the ProblemofTSP.(L2)
Travelling Sales Person Problem is a problem in which he should Visit N number of
cities with a minimumnumber of Cost by visiting every city Exactly one and the city
what he is started should end with same city.
60. What is the Concept of Dynamic Programming?(L3)
Deriving a Solution to thebasic Condition and Extracting thesolutions for therest of
the other data sets by Previously drawnd Solution.Computer to other algorithmic
Technique Dynamic Programming because it avoids lot of reworking on the same
Solution what we have solved in the earlier phases of deriving the solution to the
problem.
61. What is the goal of Warshalls Algorithm?(L3)
Warshall’s algorithm is to find the shortest distance between a node to all the other
nodes in thegraph.It Uses thePropertyofTransitiveClosurei.eifthereexist apath
between (i,k) and (k,j) then there surelyexist a path between (i,j)
(i,k)&(k,j)---◻(I,J)
62. What is the use of Floyds algorithm?(L3)
It is use to find the All pairs shortest Path of an Graph.