0% found this document useful (0 votes)
25 views35 pages

Daa Labmanual 2024-25

The document is a laboratory manual for the Analysis & Design of Algorithms Lab for the academic year 2024-25 at East Point College of Engineering and Technology. It outlines the program outcomes, educational objectives, specific outcomes, course objectives, experiments, assessment details, and suggested learning resources. The manual emphasizes the development and implementation of algorithms using C/C++ programming to solve various computational problems while adhering to evaluation criteria for practical assessments.

Uploaded by

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

Daa Labmanual 2024-25

The document is a laboratory manual for the Analysis & Design of Algorithms Lab for the academic year 2024-25 at East Point College of Engineering and Technology. It outlines the program outcomes, educational objectives, specific outcomes, course objectives, experiments, assessment details, and suggested learning resources. The manual emphasizes the development and implementation of algorithms using C/C++ programming to solve various computational problems while adhering to evaluation criteria for practical assessments.

Uploaded by

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

Department of Artificial Intelligence and Data Science

‘Jnana Prabha’, Virgo Nagar Post, Bengaluru-560049

Academic Year: 2024-25

LABORATORY MANUAL
SEMESTER :IV
SUBJECT :Analysis&Design ofAlgorithmsLab
SUBCODE :BCSL404

NAME:____________________________________________________________

USN: _____________________________________________________________

SECTION:__________________________________________________________

BATCH:___________________________________________________________
PROGRAM OUTCOMES
Engineering Graduates will able to:

Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.

Problem analysis: Identify, formulate, review research literature, and analyse complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.

Design/development of solutions: Design solutions for complex engineering problems and


design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.

Conduct investigations of complex problems: Use research-based knowledge and research


methods including design of experiments, analysis and interpretation of data, and synthesis
of the information to provide valid conclusions.

Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modelling to complex engineering
activities with an understanding of the limitations.

The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant
to the professional engineering practice.

Environment and sustainability: Understand the impact of the professional engineering


solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.

Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice. Individual and team work: Function effectively as an
individual, and as a member or leader in diverse teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give
and receive clear instructions.

Project management and finance: Demonstrate knowledge and understanding of the


Engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments.

Life -long learning: Recognize the need for and have the preparation and ability to engage in
independent and life -long learning in the broadest context of technological change.
INSTITUTE VISION AND MISSION

VISION

The East Point College of Engineering and Technology aspires to be a globally


acclaimed institution, recognized for excellence in engineering education, applied
research and nurturing students for holistic development.

MISSION

M1: To create engineering graduates through quality education and to nurture


innovation, creativity and excellence in teaching, learning and research
M2: To serve the technical, scientific, economic and societal developmental needs
of our communities
M3: To induce integrity, teamwork, critical thinking, personality development and
ethics in students and to lay the foundation for lifelong learning
Department of Artificial Intelligence and Data Science

DEPARTMENT VISION AND MISSION

VISION

The department orients towards identifying and exploring emerging global trends in
the fields of Artificial Intelligence and Data Science through academic excellence
and quality research, producingproficient professionals for a flourishing society.
MISSION
M1: To nurture students with quality education, life-long learning, values and
ethics.
M2:To produce ethical and competent professionals through comprehensive and
holistic methodologies that align with the global industry demands in Artificial
Intelligence and Data Science.

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)

1. Graduates will possess the ability to apply their knowledge of fundamental


engineering, Computer Science and Data Science.
2. Graduates will have sound intercommunication skills, ethical values and
responsibilities to work and serve for the development of the society.
3. Graduates will be able to understand, interpret, model and implement the
Artificial Intelligence and Data Science based solutions for real world
problems.

PROGRAM SPECIFIC OUTCOMES (PSOs)

1. To cater and enhance the analytical and technical skills of the graduates in
order to be ready for the professional development, research and pursue
higher education.
2. To formulate solutions for the real-world problems with the application of
basic engineering principles and technical skills of Artificial Intelligence
and Data Science.
Analysis&Design ofAlgorithmsLab Semester 4
CourseCode BCSL404 CIEMarks 50
TeachingHours/Week(L:T:P:S) 0:0:2:0 SEEMarks 50
Credits 01 ExamHours 2
Examinationtype(SEE) Practical
Courseobjectives:
● TodesignandimplementvariousalgorithmsinC/C++programmingusingsuitabledevelopmenttoolstoaddressdiffere
ntcomputational challenges.
● Toapplydiversedesignstrategiesforeffectiveproblem-solving.
● ToMeasureandcomparetheperformanceofdifferentalgorithmstodeterminetheirefficiencyandsuitabilityforspecifictasks
.
Sl.No Experiments
1 DesignandimplementC/C++Program tofind MinimumCostSpanningTreeof agivenconnected
undirectedgraphusingKruskal'salgorithm.
2 DesignandimplementC/C++Program tofind MinimumCostSpanningTreeof agivenconnected
undirectedgraphusingPrim'salgorithm.
3 a. Design and implement C/C++ Program to solve All-Pairs Shortest Paths problem using
Floyd'salgorithm.
b. DesignandimplementC/C++ProgramtofindthetransitiveclosureusingWarshal's
algorithm.
4 DesignandimplementC/C++Programtofindshortestpathsfromagivenvertexinaweighted
connectedgraphtootherverticesusingDijkstra'salgorithm.
5 DesignandimplementC/C++ProgramtoobtaintheTopologicalorderingofverticesinagiven
digraph.
6 DesignandimplementC/C++Programtosolve0/1KnapsackproblemusingDynamic
Programmingmethod.
7 DesignandimplementC/C++ProgramtosolvediscreteKnapsackandcontinuousKnapsack
problemsusinggreedyapproximationmethod.
8 DesignandimplementC/C++ProgramtofindasubsetofagivensetS={sl,s2,.....,sn}ofn
positiveintegerswhosesumisequaltoagivenpositiveintegerd.
9 Design and implement C/C++ Program to sort a given set of n integer elements using SelectionSort
method and compute its time complexity. Run the program for varied values of n> 5000
andrecordthetimetakentosort.Plotagraphofthetimetakenversusn.Theelementscanberead
fromafileorcanbegeneratedusingthe randomnumbergenerator.
10 Design and implement C/C++ Program to sort a given set of n integer elements using Quick
Sortmethod and compute its time complexity. Run the program for varied values of n> 5000
andrecordthetimetakentosort.Plotagraphofthetimetakenversusn.Theelementscanbereadfromafileorcanb
egeneratedusingthe randomnumbergenerator.
11 Design and implement C/C++ Program to sort a given set of n integer elements using Merge
Sortmethod and compute its time complexity. Run the program for varied values of n> 5000,
andrecordthetimetakentosort.Plotagraphofthetimetakenversusn.Theelementscanbereadfromafileorcanb
egeneratedusingthe random numbergenerator.
12 DesignandimplementC/C++ProgramforNQueen'sproblemusingBacktracking.
Courseoutcomes(CourseSkillSet):
Attheendofthecoursethe studentwillbeableto:
1. Developprogramstosolvecomputationalproblemsusingsuitablealgorithmdesignstrategy.
2. Compare algorithmdesign strategiesby developing equivalent programsandobservingrunningtimes
foranalysis(Empirical).
3. Makeuseofsuitableintegrateddevelopmenttoolstodevelopprograms
4. Chooseappropriatealgorithmdesigntechniquestodevelopsolutiontothecomputationalandcomplexproble
ms.
5. Demonstrateandpresentthedevelopmentofprogram,itsexecutionandrunningtime(s)and
recordtheresults/inferences.
AssessmentDetails(bothCIEandSEE)
The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is 50%.The
minimum passing mark for the CIE is 40% of the maximum marks (20 marks out of 50) and for theSEE
minimum passing mark is 35% of the maximum marks (18 out of 50 marks). A student shall bedeemed to have
satisfied the academic requirements and earned the credits allotted to each subject/course if the student secures
a minimum of 40% (40 marks out of 100) in the sum total of the CIE(Continuous
InternalEvaluation)andSEE(SemesterEndExamination)takentogether

ContinuousInternalEvaluation(CIE):
CIEmarksforthepracticalcourseare50Marks.
Thesplit-upofCIEmarksforrecord/journalandtestareintheratio 60:40.
● Each experiment is to be evaluated for conduction with an observation sheet and record write-
up.Rubrics for the evaluation of the journal/write-up for hardware/software experiments aredesigned by
the faculty who is handling the laboratory session and are made known to students atthebeginningof the
practicalsession.
● Record should contain all the specified experiments in the syllabus and each experiment write-
upwillbeevaluated for10 marks.
● Totalmarksscoredbythestudentsarescaleddownto 30marks(60%ofmaximummarks).
● Weightagetobegivenforneatnessandsubmissionofrecord/write-upontime.
● Department shall conduct a test of 100 marks after the completion of all the experiments listed
inthesyllabus.
● In a test, test write-up, conduction of experiment, acceptable result, and procedural knowledge
willcarryaweightageof60%andtherest40% forviva-voce.
● Thesuitablerubricscanbedesignedtoevaluateeachstudent’sperformanceandlearningability.
● Themarks scoredshallbescaleddownto 20marks(40%ofthemaximummarks).
The Sumofscaled-downmarksscoredinthereportwrite-up/journalandmarksofatest isthetotalCIEmarks scored
bythestudent.

SemesterEndEvaluation(SEE):
● SEEmarksforthepracticalcourseare50Marks.
● SEEshallbeconductedjointlybythetwoexaminersofthesameinstitute,examinersareappointedbytheHeadoft
heInstitute.
● The examination schedule and names of examiners are informed to the university before theconduction
of the examination. These practical examinations are to be conducted between
theschedulementionedinthe academiccalendarof theUniversity.
● Alllaboratoryexperimentsaretobeincludedforpracticalexamination.
● (Rubrics) Breakup of marks and the instructions printed on the cover page of the answer scriptto be
strictly adhered to by the examiners.OR based on the course requirement evaluationrubricsshallbe
decidedjointlybyexaminers.
● Students can pick one question (experiment) from the questions lot prepared by the examinersjointly.
● Evaluation of test write-up/ conduction procedure and result/viva will be conducted jointly
byexaminers.
General rubrics suggested for SEE are mentioned here, writeup-20%, Conduction procedure andresult in -
60%, Viva-voce 20% of maximum marks. SEE for practical shall be evaluated for 100 marksand scored
marks shall be scaled down to 50 marks (however, based on course type, rubrics shall bedecidedbythe
examiners)
Change of experiment is allowed only once and 15% of Marks allotted to the procedure part are to
bemadezero.
TheminimumdurationofSEEis02hours

SuggestedLearningResources:
● VirtualLabs(CSE):http://cse01-iiith.vlabs.ac.in/
Index

SI. Page
ProgramsList: CO PO RBT No.
No.
1 DesignandimplementC/C++Program tofind MinimumCostSpanningTreeof
agivenconnectedundirectedgraphusingKruskal'salgorithm. CO1 PO2 L2 4
2 DesignandimplementC/C++Program tofind MinimumCostSpanningTreeof
agivenconnectedundirectedgraphusingPrim'salgorithm. CO1 PO2 L2 7

Design and implement C/C++ Program to solve All-Pairs Shortest Paths


3a. problem using Floyd'salgorithm.
CO1 PO3 L2 11

b. DesignandimplementC/C++ProgramtofindthetransitiveclosureusingWarshal
'salgorithm. CO1 PO3 L2 15
4. DesignandimplementC/C++Programtofindshortestpathsfromagivenvertexi
naweightedconnectedgraphtootherverticesusingDijkstra'salgorithm. CO1 PO3 L3 18

5. DesignandimplementC/C++ProgramtoobtaintheTopologicalorderingofvert
icesinagivendigraph.
CO1 PO3 L3 20
6. DesignandimplementC/C++Programtosolve0/1KnapsackproblemusingDyn
amicProgrammingmethod. CO2 PO3 L4 24

DesignandimplementC/C++ProgramtosolvediscreteKnapsackandcontinuo
7. usKnapsackproblemsusinggreedyapproximationmethod. CO2
PO3 L4 29

8. DesignandimplementC/C++ProgramtofindasubsetofagivensetS={sl,s2,....., CO3
sn}ofnpositiveintegerswhosesumisequaltoagivenpositiveintegerd. PO3 L3 34

Design and implement C/C++ Program to sort a given set of n integer


9. elements using SelectionSort method and compute its time complexity.
Run the program for varied values of n> 5000
andrecordthetimetakentosort.Plotagraphofthetimetakenversusn.Theeleme
ntscanberead
fromafileorcanbegeneratedusingthe randomnumbergenerator.
Design and implement C/C++ Program to sort a given set of n integer
10. elements using Quick Sortmethod and compute its time complexity. Run
the program for varied values of n> 5000
andrecordthetimetakentosort.Plotagraphofthetimetakenversusn.Theeleme
ntscanbereadfromafileorcanbegeneratedusingthe
randomnumbergenerator.
11. Design and implement C/C++ Program to sort a given set of n integer
elements using Merge Sortmethod and compute its time complexity. Run
the program for varied values of n> 5000,
andrecordthetimetakentosort.Plotagraphofthetimetakenversusn.Theeleme
ntscanberead
fromafileorcanbegeneratedusingthe random numbergenerator.
12. DesignandimplementC/C++ProgramforNQueen'sproblemusingBacktrac
king.
DesignandAnalysisofAlgorithms
Laboratory BCSL404

PROGRAMS

DEPTOFAI&DS,EPCET Page1
DesignandanalysisofAlgorithms 21CS42
WhatisAlgorithm?
A finite set of instruction that specifies a sequence of operation is to be carried out in order
tosolve a specific problemorclass ofproblemsiscalledanAlgorithm.

WhystudyAlgorithm?

Asthespeedofprocessorincreases,performanceisfrequentlysaidtobelesscentralthanothersoftwar
equalitycharacteristics(e.g.security,extensibility,reusabilityetc.).However,largeproblemsizesar
ecommonplaceintheareaofcomputationalscience,whichmakesperformanceavery
importantfactor.Thisisbecauselongercomputation
time,tonameafewmeanslowerresults,ThestudyofAlgorithm,therefore,givesusalanguagetoexpre
ssperformance as afunctionofproblemsize.

Analgorithmmusthavethefollowi
ngproperties:

o Correctness:Itshouldproducetheoutputaccordingtotherequirementofthealgorit
hm
o Finiteness:Algorithmmustcompleteafterafinite
numberofinstructionshavebeenexecuted.
o Definiteness:Eachstepmustbedefined,havingonlyoneinterpretation.
o Input/output:Numberandclassificationofneededinputsandresults mustbestated.
o Feasibility:Itmustbefeasibleto executeeachinstruction.
o Flexibility:Itshouldalsobepossibletomakechangesinthealgorithmwithoutputtingsomuc
heffortonit.
o Efficient-Efficiencyisalwaysmeasuredintermsoftimeandspacerequiresimplementing
the algorithm, so the algorithm uses a little running time and memoryspace aspossible
withinthelimitsofacceptable developmenttime.

ComplexityofAlgorithm

It is very convenient to classify algorithm based on the relative amount of time or


relativeamount of space they required and specify the growth of time/space requirement as a
functionofinputsize.

TimeComplexity:Runningtimeof aprogramasafunctionof the size oftheinput.

Space Complexity: Some forms of analysis could be done based on how much space
analgorithm needs to complete its task. This space complexity analysis was critical in the
earlydaysofcomputingwhenstoragespaceonthe computerwas limited.

Thefollowing aretetypesofanalysis

Worst-case: f(n)definedbythemaximum numberofstepstakenonanyinstance ofsizen.Best-


case:f(n)defined bytheminimumnumberofstepstakenonany instanceofsizen.
Average case:f(n)definedbythe averagenumberofstepstakenonanyinstance ofsizen.

, Page2
AlgorithmDesignTechniques
Thefollowingisalistofseveralpopulardesignapproaches:
1. Divide and Conquer Approach: It is a top-down approach. The algorithms which followthe
divide&conquertechniquesinvolve threesteps:

o Dividetheoriginalproblemintoasetofsubproblems.
o Solveeverysubproblemindividually,recursively.
o Combinethesolutionofthesubproblems(toplevel)intoasolutionof
thewholeoriginalproblem.

2. GreedyTechnique:Greedymethodis usedtosolvetheoptimizationproblem.Anoptimization problem


is one in which we are given a set of input values, which are
requiredeithertobemaximizedorminimized(knownasobjective),i.e.someconstraintsorconditions.3.
DynamicProgramming:DynamicProgrammingisabottom-
upapproachwesolveallpossiblesmallproblemsandthencombinethemtoobtainsolutionsforbigger
problems.Thisisparticula
rlyhelpfulwhenthenumberofcopyingsubproblemsisexponentiallylarge.DynamicProgrammingisfrequent
lyrelatedtoOptimizationProblems.
4. Branch and Bound: In Branch & Bound algorithm a given subproblem, which cannot bebounded,
has to be divided into at least two new restricted subproblems. Branch and Boundalgorithm are
methods for global optimization in non-convex problems. Branch and
Boundalgorithmscanbeslow,howeverintheworstcasetheyrequireeffortthatgrowsexponentiallywithprobl
emsize, butinsomecaseswearelucky, andthemethodcoveragewithmuchlesseffort.
5. BacktrackingAlgorithm:BacktrackingAlgorithmtrieseach possibilityuntil they
findtherightone.Itisadepth-
firstsearchofthesetofpossiblesolution.Duringthesearch,ifanalternativedoesn'twork,thenbacktracktothec
hoicepoint,theplacewhichpresenteddifferentalternatives,andtriesthenextalternative.
6. RandomizedAlgorithm:Arandomizedalgorithmusesarandomnumberatleastonceduringthecomputat
ionmakeadecision.
Example1:InQuick Sort,usingarandomnumbertochooseapivot.
Example2:Tryingtofactoralargenumberbychoosingarandomnumberaspossibledivisors.
1. Design and implement C/C++ Program to find Minimum Cost Spanning Tree of a given connected undirected
graph using Kruskal's algorithm

#include<iostream>
#include<string.h>
using namespace std;
class Graph
{
char vertices[10][10];
int cost[10][10],no;
public:
Graph();
void creat_graph();
void display();
int Position(char[]);
void kruskal_algo();
};
/* Initialzing adj matrix with 999 */
/* 999 denotes infinite distance */
Graph::Graph()
{
no=0;
for(int i=0;i<10;i++)
for(int j=0;j<10;j++)
{
cost[i][j]=999;
}
}
/* Taking inputs for creating graph */
void Graph::creat_graph()
{
char ans,Start[10],End[10];
int wt,i,j;
cout<<"Enter the number of vertices: ";
cin>>no;
cout<<"\nEnter the vertices: ";
for(i=0;i<no;i++)
cin>>vertices[i];
do
{
cout<<"\nEnter Start and End vertex of the edge: ";
cin>>Start>>End;
cout<<"Enter weight: ";
cin>>wt;
i=Position(Start);
j=Position(End);
cost[i][j]=cost[j][i]=wt;
cout<<"\nDo you want to add more edges (Y=YES/N=NO)? : "; /* Type 'Y' or 'y' for YES and 'N' or 'n' for
NO */
cin>>ans;
}while(ans=='y' || ans=='Y');
}
/* Displaying Cost matrix */
void Graph::display()
{
int i,j;
cout<<"\n\nCost matrix: ";
for(i=0;i<no;i++)
{
cout<<"\n";
for(j=0;j<no;j++)
cout<<"\t"<<cost[i][j];
}
}
/* Retrieving position of vertices in 'vertices' array */
int Graph::Position(char key[10])
{
int i;
for(i=0;i<10;i++)
if(strcmp(vertices[i],key)==0)
return i;
return -1;
}
void Graph::kruskal_algo()
{
int i,j,v[10]={0},x,y,Total_cost=0,min,gr=1,flag=0,temp,d;
while(flag==0)
{
min=999;
for(i=0;i<no;i++)
{
for(j=0;j<no;j++)
{
if(cost[i][j]<min)
{
min=cost[i][j];
x=i;
y=j;
}
}
}

if(v[x]==0 && v[y]==0)


{
v[x]=v[y]=gr;
gr++;
}
else if(v[x]!=0 && v[y]==0)
v[y]=v[x];
else if(v[x]==0 && v[y]!=0)
v[x]=v[y];
else
{
if(v[x]!=v[y])
{
d=v[x];
for(i=0;i<no;i++)
{
if(v[i]==d)
v[i]=v[y];
}//end for
}
}

cost[x][y]=cost[y][x]=999;
Total_cost=Total_cost+min; /* calculating cost of minimum spanning tree */
cout<<"\n\t"<<vertices[x]<<"\t\t"<<vertices[y]<<"\t\t"<<min;

temp=v[0]; flag=1;
for(i=0;i<no;i++)
{
if(temp!=v[i])
{
flag=0;
break;
}
}
}
cout<<"\nTotal cost of the tree= "<<Total_cost;
}
int main()
{
Graph g;
g.creat_graph();
g.display();
cout<<"\n\n\nMinimum Spanning tree using kruskal algo=>";
cout<<"\nSource vertex\tDestination vertex\tWeight\n";
g.kruskal_algo();
return 0;
}

OUTPUT

Enter the number of vertices: 5


Enter the vertices: 0 1 2 3 4

Enter Start and End vertex of the edge: 0


1
Enter weight: 2

Do you want to add more edges (Y=YES/N=NO)? : y

Enter Start and End vertex of the edge: 1


2
Enter weight: 3

Do you want to add more edges (Y=YES/N=NO)? : y

Enter Start and End vertex of the edge: 1


4
Enter weight: 5

Do you want to add more edges (Y=YES/N=NO)? : y

Enter Start and End vertex of the edge: 2


4
Enter weight: 7

Do you want to add more edges (Y=YES/N=NO)? : y

Enter Start and End vertex of the edge: 0


3
Enter weight: 6

Do you want to add more edges (Y=YES/N=NO)? : y

Enter Start and End vertex of the edge: 1


3
Enter weight: 8

Do you want to add more edges (Y=YES/N=NO)? : y

Enter Start and End vertex of the edge: 3


4
Enter weight: 9
Do you want to add more edges (Y=YES/N=NO)? : n

Cost matrix:
999 2 999 6 999
2 999 3 8 5
999 3 999 999 7
6 8 999 999 9
999 5 7 9 999

Minimum Spanning tree using kruskal algo=>


Source vertex Destination vertex Weight
0 1 2
1 2 3
1 4 5
0 3 6
Total cost of the tree= 16

2. Design and implement C/C++ Program to find Minimum Cost Spanning Tree of a given connected undirected
graph using Prim's algorithm.
#include<stdio.h>
int main()
{
int cost[10][10],visited[10]={0},i,j,n,no_e=1,min,a,b,min_cost=0;
printf("Enter number of nodes ");
scanf("%d",&n);
printf("Enter cost in form of adjacency matrix\n");
//input graph
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
// cost is 0 then initialize it by maximum value
if(cost[i][j]==0)
cost[i][j]=1000;
}
}

// logic for finding minimum cost spanning tree


visited[1]=1; // visited first node
while(no_e<n)
{
min=1000;
// in each cycle find minimum cost
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min)
{
if(visited[i]!=0)
{
min=cost[i][j];
a=i;
b=j;
}
}
}
}
//if node is not visited
if(visited[b]==0)
{
printf("\n%d to %d cost=%d",a,b,min);
min_cost=min_cost+min;
no_e++;
}
visited[b]=1;
// initialize with maximum value you can also use any other value
cost[a][b]=cost[b][a]=1000;
}
printf("\nminimum weight is %d",min_cost);
return 0;
}

Output:-

Enter number of nodes 6


Enter cost in form of adjacency matrix
044000
402000
420324
003003
002003
004330

1 to 2 cost=4
2 to 3 cost=2
3 to 5 cost=2
3 to 4 cost=3
4 to 6 cost=3
minimum weight is 14

3.a. Design and implement C/C++ Program to solve All-Pairs Shortest Paths problem using Floyd's algorithm.

#include <iostream>
#include <cstdlib>
#define max 10
#define infi 999
using namespace std;
int p[max][max];
/*
* All Pairs Shortest Path using Floyd's Algorithm
*/
void allpairshort(int a[max][max], int n)
{
int k, i, j;
for (k = 0; k < n; k++)
{
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (a[i][k] + a[k][j] < a[i][j])
{
a[i][j] = a[i][k] + a[k][j];
p[i][j] = k;
}
}
}
}
}

/*
* Storing the shortest path
*/
void shortest(int i, int j)
{
int k = p[i][j];
if (k > 0)
{
shortest(i, k);
cout<<" "<<k<<" ";
shortest(k, j);
}
}
/*
* Display the Shortest Path
*/
void findpath(int a[max][max], int i, int j, int n)
{
cout<<"Path from " << i <<" to "<< j << ":";
if (a[i][j] < infi)
{
cout<<" "<<i<<" ";
shortest(i, j);
cout<<" "<<j<<" ";
}
}
/*
* Main Contains Menu
*/
int main()
{
int i, j;
int a[][10] = {{0, 10, infi, 30, 100},
{infi, 0 , 50, infi, infi},
{infi, infi , 0, infi, 10},
{infi, infi , 20, 0, 60},
{infi, infi , infi, infi, 0},
};

allpairshort(a, 5);
findpath(a, 0, 4, 5);
return 0;
}

Output
Path from 0 to 4: 0 3 2 4

3b.Design and implement C/C++ Program to find the transitive closure using Warshal's algorithm.

#include<iostream>

using namespace std;


const int num_nodes = 10;

int main()
{
int num_nodes, k, n;
char i, j, res, c;
int adj[10][10], path[10][10];

cout << "\n\tMaximum number of nodes in the graph :";


cin >> n;
num_nodes = n;
cout << "\n\n\tNODES ARE LABELED AS A,B,C,......\n\n";
cout << "\nEnter 'y'for 'YES' and 'n' for 'NO' !!\n";
for (i = 65; i < 65 + num_nodes; i++)
for (j = 65; j < 65 + num_nodes; j++)
{
cout << "\n\tIs there an EDGE from " << i << " to " << j << " ? ";
cin >> res;
if (res == 'y')
adj[i - 65][j - 65] = 1;
else
adj[i - 65][j - 65] = 0;
}
cout << "\nAdjacency Matrix:\n";

cout << "\n\t\t\t ";


for (i = 0; i < num_nodes; i++)
{
c = 65 + i;
cout << c << " ";
}
cout << "\n\n";
for (int i = 0; i < num_nodes; i++)
{
c = 65 + i;
cout << "\t\t\t" << c << " ";
for (int j = 0; j < num_nodes; j++)
cout << adj[i][j] << " ";
cout << "\n";
}
for (int i = 0; i < num_nodes; i++)
for (int j = 0; j < num_nodes; j++)
path[i][j] = adj[i][j];

for (int k = 0; k < num_nodes; k++)


for (int i = 0; i < num_nodes; i++)
if (path[i][k] == 1)
for (int j = 0; j < num_nodes; j++)
path[i][j] = path[i][j] || path[k][j];

for (int i = 0; i < num_nodes; i++)


for (int j = 0; j < num_nodes; j++)
adj[i][j] = path[i][j];

cout << "\nTransitive Closure of the Graph:\n";

cout << "\n\t\t\t ";


for (i = 0; i < num_nodes; i++)
{
c = 65 + i;
cout << c << " ";
}
cout << "\n\n";
for (int i = 0; i < num_nodes; i++)
{

c = 65 + i;
cout << "\t\t\t" << c << " ";
for (int j = 0; j < num_nodes; j++)
cout << adj[i][j] << " ";
cout << "\n";
}
return 0;
}
Output
Maximum number of nodes in the graph :4

NODES ARE LABELED AS A,B,C,......

Enter 'y'for 'YES' and 'n' for 'NO' !!

Is there an EDGE from A to A ? y

Is there an EDGE from A to B ? n

Is there an EDGE from A to C ? y

Is there an EDGE from A to D ? n

Is there an EDGE from B to A ? n

Is there an EDGE from B to B ? y

Is there an EDGE from B to C ? y

Is there an EDGE from B to D ? y

Is there an EDGE from C to A ? y

Is there an EDGE from C to B ? n

Is there an EDGE from C to C ? y

Is there an EDGE from C to D ? y

Is there an EDGE from D to A ?


n

Is there an EDGE from D to B ? y

Is there an EDGE from D to C ? y

Is there an EDGE from D to D ? y

Adjacency Matrix:

ABCD

A 1010
B 0111
C 1011
D 0111

Transitive Closure of the Graph:

ABCD
A 1111
B 1111
C 1111
D 1111
4.Design and implement C/C++ Program to find shortest paths from a given vertex in a weighted connected graph to other
vertices using Dijkstra's algorithm.
#include <limits.h>
#include <stdio.h>
#define V 9
int minDistance(int dist[], bool sptSet[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false &&dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
int printSolution(int dist[], int n) {
printf("Vertex Distance from Source\n");
for (int i = 0; i< V; i++)
printf("%d \t %d\n", i, dist[i]);
return 0;
}
void dijkstra(int graph[V][V], int src) {
int dist[V];
bool sptSet[V];
for (int i = 0; i< V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] &&dist[u] != INT_MAX &&dist[u] + graph[u][v] <dist[v]) dist[v] = dist[u] +
graph[u][v];
}
printSolution(dist, V);
}
int main() {
int graph[V][V] = { { 0, 6, 0, 0, 0, 0, 0, 8, 0 },
{ 6, 0, 8, 0, 0, 0, 0, 13, 0 },
{ 0, 8, 0, 7, 0, 6, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 6, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 13, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 }
};
dijkstra(graph, 0);
return 0;
}
Output
Vertex Distance from Source
00
16
2 14
3 21
4 21
5 11
69
78
8 15

5.Design and implement C/C++ 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));
flag [k]=1;
}

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

count++;
}

return 0;
}
Output

Enter the no of vertices:


4
Enter the adjacency matrix:
Enter row 1
0110
Enter row 2
0001
Enter row 3
0001
Enter row 4
0000

The topological order is:1 2 3 4

6.Design and implement C/C++ Program to solve 0/1 Knapsack problem using Dynamic Programming method.
#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:");


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

Enter number of items:3


Enter value and weight of items:
100 20
50 10
150 30
Enter size of knapsack:50
250

7. Design and implement C/C++ Program to solve discrete Knapsack and continuous Knapsack problems using greedy
approximation method.

a. Continous Knapsack Problem


#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct Item {
int weight;
int value;
double ratio; // value-to-weight ratio

Item(int w, int v) : weight(w), value(v), ratio((double)v / w) {}


};

// Comparator function to sort items based on value-to-weight ratio


bool compareItems(const Item &a, const Item &b) {
return a.ratio>b.ratio;
}

double fractionalKnapsack(int capacity, vector<Item>&items) {


sort(items.begin(), items.end(), compareItems);

double totalValue = 0.0;


for (const auto &item : items) {
if (capacity == 0)
break;

int weightToAdd = min(item.weight, capacity);


totalValue += weightToAdd * item.ratio;
capacity -= weightToAdd;
}

return totalValue;
}

int main() {
int capacity;
cout<< "Enter the capacity of the knapsack: ";
cin>> capacity;

int n;
cout<< "Enter the number of items: ";
cin>> n;

vector<Item> items;
cout<< "Enter weight and value for each item:\n";
for (int i = 0; i< n; ++i) {
int weight, value;
cin>> weight >> value;
items.push_back(Item(weight, value));
}
double maxValue = fractionalKnapsack(capacity, items);
cout<< "Maximum value that can be obtained: " <<maxValue<<endl;

return 0;
}

Output

Enter the capacity of the knapsack: 50


Enter the number of items: 3
Enter weight and value for each item:
10 60
20 100
30 120
Maximum value that can be obtained: 240

b.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct Item {
int weight;
int value;

Item(int w, int v) : weight(w), value(v) {}


};

bool compareItems(const Item &a, const Item &b) {


return (a.value>b.value);
}

int knapsack(int capacity, vector<Item>&items) {


sort(items.begin(), items.end(), compareItems);

int totalValue = 0;
for (const auto &item : items) {
if (capacity == 0)
break;

if (item.weight<= capacity) {
totalValue += item.value;
capacity -= item.weight;
}
}

return totalValue;
}

int main() {
int capacity;
cout<< "Enter the capacity of the knapsack: ";
cin>> capacity;

int n;
cout<< "Enter the number of items: ";
cin>> n;
vector<Item> items;
cout<< "Enter weight and value for each item:\n";
for (int i = 0; i< n; ++i) {
int weight, value;
cin>> weight >> value;
items.push_back(Item(weight, value));
}

int maxValue = knapsack(capacity, items);


cout<< "Maximum value that can be obtained: " <<maxValue<<endl;

return 0;
}

Output
Enter the number of items: 5
Enter weight and value for each item:
10 60
20 100
30 120
5 50
15 70
Maximum value that can be obtained: 330

8. Design and implement c/c++ program to find a subset of a given set S={s1,s2,...,sn} of n positive integer whose sum is
equal to given positive integer d

#include<stdio.h>
#include<stdlib.h>
staticinttotal_nodes;
voidprintValues(int A[],int size){
for(inti=0;i< size;i++){
printf("%*d",5, A[i]);
}
printf("\n");
}
voidsubset_sum(int s[],int t[],ints_size,intt_size,int
sum,intite,intconsttarget_sum){
total_nodes++;
if(target_sum== sum){
printValues(t,t_size);
subset_sum(s, t,s_size,t_size-1, sum -
s[ite],ite+1,target_sum);
return;
}
else{
for(inti=ite;i<s_size;i++){
t[t_size]= s[i];
subset_sum(s, t,s_size,t_size+1, sum +
s[i],i+1,target_sum);
}
}
}
voidgenerateSubsets(int s[],int size,inttarget_sum){
int*tuplet_vector=(int*)malloc(size *sizeof(int));
subset_sum(s,tuplet_vector, size,0,0,0,target_sum);
free(tuplet_vector);
}
intmain(){
intset[]={5,6,12,54,2,20,15};
int size =sizeof(set)/sizeof(set[0]);
printf("The set is ");
printValues(set, size);
generateSubsets(set, size,25);
printf("Total Nodes generated %d\n",total_nodes);
return0;
}

Output
The set is 5 6 12 54 2 20 15
5 6 12 2
5 20
Total Nodes generated 127

9.Design and implement C/C++ Program to sort a given set of n integer elements using SelectionSort method and
compute its time complexity. Run the program for varied values of n> 5000
andrecordthetimetakentosort.Plotagraphofthetimetakenversusn.Theelementscanberead
fromafileorcanbegeneratedusingthe randomnumbergenerator.

#include <bits/stdc++.h>
usingnamespacestd;

//Swap function
voidswap(int*xp, int*yp)
{
inttemp = *xp;
*xp = *yp;
*yp = temp;
}

voidselectionSort(intarr[], intn)
{
inti, j, min_idx;

// One by one move boundary of


// unsorted subarray
for(i = 0; i< n-1; i++)
{

// Find the minimum element in


// unsorted array
min_idx = i;
for(j = i+1; j < n; j++)
if(arr[j] <arr[min_idx])
min_idx = j;

// Swap the found minimum element


// with the first element
swap(&arr[min_idx], &arr[i]);
}
}

//Function to print an array


voidprintArray(intarr[], intsize)
{
inti;
for(i=0; i< size; i++)
cout<<arr[i] <<" ";
cout<<endl;
}

// Driver program to test above functions


intmain()
{
intarr[] = {64, 25, 12, 22, 11};
intn = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
cout<<"Sorted array: ";
printArray(arr, n);
return0;
}

Output
Sorted array:
11 12 22 25 64

10.Design and implement C/C++ Program to sort a given set of n integer elements using Merge Sortmethod and
compute its time complexity. Run the program for varied values of n> 5000,
andrecordthetimetakentosort.Plotagraphofthetimetakenversusn.Theelementscanberead
fromafileorcanbegeneratedusingthe random numbergenerator.
// C++ program for Merge Sort
#include <iostream>
usingnamespacestd;

// Merges two subarrays of array[].


// First subarray is arr[begin..mid]
// Second subarray is arr[mid+1..end]
voidmerge(intarray[], intconstleft,
intconstmid, intconstright)
{
autoconstsubArrayOne = mid - left + 1;
autoconstsubArrayTwo = right - mid;

// Create temp arrays


auto*leftArray = newint[subArrayOne],
*rightArray = newint[subArrayTwo];

// Copy data to temp arrays leftArray[]


// and rightArray[]
for(autoi = 0; i<subArrayOne; i++)
leftArray[i] = array[left + i];
for(autoj = 0; j <subArrayTwo; j++)
rightArray[j] = array[mid + 1 + j];

// Initial index of first sub-array


// Initial index of second sub-array
autoindexOfSubArrayOne = 0,
indexOfSubArrayTwo = 0;

// Initial index of merged array


intindexOfMergedArray = left;

// Merge the temp arrays back into


// array[left..right]
while(indexOfSubArrayOne<subArrayOne&&
indexOfSubArrayTwo<subArrayTwo)
{
if(leftArray[indexOfSubArrayOne] <=
rightArray[indexOfSubArrayTwo])
{
array[indexOfMergedArray] =
leftArray[indexOfSubArrayOne];
indexOfSubArrayOne++;
}
else
{
array[indexOfMergedArray] =
rightArray[indexOfSubArrayTwo];
indexOfSubArrayTwo++;
}
indexOfMergedArray++;
}

// Copy the remaining elements of


// left[], if there are any
while(indexOfSubArrayOne<subArrayOne)
{
array[indexOfMergedArray] =
leftArray[indexOfSubArrayOne];
indexOfSubArrayOne++;
indexOfMergedArray++;
}

// Copy the remaining elements of


// right[], if there are any
while(indexOfSubArrayTwo<subArrayTwo)
{
array[indexOfMergedArray] =
rightArray[indexOfSubArrayTwo];
indexOfSubArrayTwo++;
indexOfMergedArray++;
}
}
// begin is for left index and end is
// right index of the sub-array
// of arr to be sorted */
voidmergeSort(intarray[],
intconstbegin,
intconstend)
{
// Returns recursively
if(begin >= end)
return;

automid = begin + (end - begin) / 2;


mergeSort(array, begin, mid);
mergeSort(array, mid + 1, end);
merge(array, begin, mid, end);
}

// UTILITY FUNCTIONS
// Function to print an array
voidprintArray(intA[], intsize)
{
for(autoi = 0; i< size; i++)
cout<< A[i] <<" ";
cout<<endl;
}

// Driver code
intmain()
{
intarr[] = { 12, 11, 13, 5, 6, 7 };
autoarr_size = sizeof(arr) / sizeof(arr[0]);

cout<<"Given array is "<<endl;


printArray(arr, arr_size);

mergeSort(arr, 0, arr_size - 1);

cout<<"Sorted array is "<<endl;


printArray(arr, arr_size);
return0;
}

Output
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13

11.Design and implement C/C++ Program to sort a given set of n integer elements using Quick Sortmethod and
compute its time complexity. Run the program for varied values of n> 5000
andrecordthetimetakentosort.Plotagraphofthetimetakenversusn.Theelementscanberead
fromafileorcanbegeneratedusingthe randomnumbergenerator.
// Quick sort in C++

#include <iostream>
using namespace std;

// function to swap elements


void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}

// function to print the array


void printArray(int array[], int size) {
int i;
for (i = 0; i< size; i++)
cout<< array[i] << " ";
cout<<endl;
}

// function to rearrange array (find the partition point)


int partition(int array[], int low, int high) {

// select the rightmost element as pivot


int pivot = array[high];

// pointer for greater element


int i = (low - 1);

// traverse each element of the array


// compare them with the pivot
for (int j = low; j < high; j++) {
if (array[j] <= pivot) {

// if element smaller than pivot is found


// swap it with the greater element pointed by i
i++;

// swap element at i with element at j


swap(&array[i], &array[j]);
}
}

// swap pivot with the greater element at i


swap(&array[i + 1], &array[high]);

// return the partition point


return (i + 1);
}

void quickSort(int array[], int low, int high) {


if (low < high) {
// find the pivot element such that
// elements smaller than pivot are on left of pivot
// elements greater than pivot are on righ of pivot
int pi = partition(array, low, high);

// recursive call on the left of pivot


quickSort(array, low, pi - 1);

// recursive call on the right of pivot


quickSort(array, pi + 1, high);
}
}

// Driver code
int main() {
int data[] = {8, 7, 6, 1, 0, 9, 2};
int n = sizeof(data) / sizeof(data[0]);

cout<< "Unsorted Array: \n";


printArray(data, n);

// perform quicksort on data


quickSort(data, 0, n - 1);

cout<< "Sorted array in ascending order: \n";


printArray(data, n);
}

Output

Unsorted Array:
8761092
Sorted array in ascending order:
0126789

12.DesignandimplementC/C++ProgramforNQueen'sproblemusingBacktracking.

#include <bits/stdc++.h>
#define N 4
using namespace std;

// A utility function to print solution


void printSolution(int board[N][N])
{
for (int i = 0; i< N; i++) {
for (int j = 0; j < N; j++)
if(board[i][j])
cout<< "Q ";
else cout<<". ";
printf("\n");
}
}

// A utility function to check if a queen can


// be placed on board[row][col]. Note that this
// function is called when "col" queens are
// already placed in columns from 0 to col -1.
// So we need to check only left side for
// attacking queens
bool isSafe(int board[N][N], int row, int col)
{
int i, j;

// Check this row on left side


for (i = 0; i< col; i++)
if (board[row][i])
return false;

// Check upper diagonal on left side


for (i = row, j = col; i>= 0 && j >= 0; i--, j--)
if (board[i][j])
return false;

// Check lower diagonal on left side


for (i = row, j = col; j >= 0 &&i< N; i++, j--)
if (board[i][j])
return false;

return true;
}

// A recursive utility function to solve N


// Queen problem
bool solveNQUtil(int board[N][N], int col)
{
// base case: If all queens are placed
// then return true
if (col >= N)
return true;

// Consider this column and try placing


// this queen in all rows one by one
for (int i = 0; i< N; i++) {

// Check if the queen can be placed on


// board[i][col]
if (isSafe(board, i, col)) {

// Place this queen in board[i][col]


board[i][col] = 1;

// recur to place rest of the queens


if (solveNQUtil(board, col + 1))
return true;
// If placing queen in board[i][col]
// doesn't lead to a solution, then
// remove queen from board[i][col]
board[i][col] = 0; // BACKTRACK
}
}

// If the queen cannot be placed in any row in


// this column col then return false
return false;
}

// This function solves the N Queen problem using


// Backtracking. It mainly uses solveNQUtil() to
// solve the problem. It returns false if queens
// cannot be placed, otherwise, return true and
// prints placement of queens in the form of 1s.
// Please note that there may be more than one
// solutions, this function prints one of the
// feasible solutions.
bool solveNQ()
{
int board[N][N] = { { 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };

if (solveNQUtil(board, 0) == false) {
cout<< "Solution does not exist";
return false;
}

printSolution(board);
return true;
}

// Driver program to test above function


int main()
{

solveNQ();
return 0;
}

Output

. . Q .
Q . . .
. . . Q
. Q . .

You might also like