Depth First Search (DFS) C++ Program To Traverse A Graph ...
文章推薦指數: 80 %
BFS vs DFS ; Stands for “Breadth-first search”, Stands for “Depth-first search” ; The nodes are explored breadth wise level by level. The nodes ...
Skiptocontent
Menu
MENUMENUHomeResourcesFREEeBooksQATesting
FreeQATrainingTestCasesSDLCTestLink
SoftwareTestingBugZillaMobileTestingJIRA
AgileMethodologyDatabaseTestingETLTesting
QualityAssuranceTestManagementSAPERPTesting
Courses
SoftwareTesting(LIVECourse)Selenium(LIVECourse)
SoftwareTestingSeleniumQTP/UFTJIRAVideosRubyCucumber
Automation
AutomationTestingSoapUIJIRAAppiumKarateFramework
SeleniumQTP/UFTALMQCPostman
JMeterLoadRunnerAPITestingRobotFramework
TestNGJUnitEclipseMaven
TypesOfTesting
AllTestingTypesRegressionTestingUnitTestingSmokeTesting
FunctionalTestingIntegrationTestingSystemTestingUsabilityTesting
UATTestingBetaTestingBlackBoxTestingWhiteBoxtesting
LoadTestingStressTestingSecurityTestingPerformanceTesting
Tutorials
C++C#DevOpsVBScriptTeamManagementComputerNetworkingJest
PythonJAVAUNIXSVNAngularJSSpockLaravel
SpecFlowJSONFlaskSOAtestMockitoKarma
MachineLearningBlockchainGitHubGatlingWiremock
Data
OraclePL/SQL
DataWarehouseExcelVBA
BigDataJDBC
MongoDB
Menu
MENUMENUHomeResourcesFREEeBooksQATesting
FreeQATrainingTestCasesSDLCTestLink
SoftwareTestingBugZillaMobileTestingJIRA
AgileMethodologyDatabaseTestingETLTesting
QualityAssuranceTestManagementSAPERPTesting
Courses
SoftwareTesting(LIVECourse)Selenium(LIVECourse)
SoftwareTestingSeleniumQTP/UFTJIRAVideosRubyCucumber
Automation
AutomationTestingSoapUIJIRAAppiumKarateFramework
SeleniumQTP/UFTALMQCPostman
JMeterLoadRunnerAPITestingRobotFramework
TestNGJUnitEclipseMaven
TypesOfTesting
AllTestingTypesRegressionTestingUnitTestingSmokeTesting
FunctionalTestingIntegrationTestingSystemTestingUsabilityTesting
UATTestingBetaTestingBlackBoxTestingWhiteBoxtesting
LoadTestingStressTestingSecurityTestingPerformanceTesting
Tutorials
C++C#DevOpsVBScriptTeamManagementComputerNetworkingJest
PythonJAVAUNIXSVNAngularJSSpockLaravel
SpecFlowJSONFlaskSOAtestMockitoKarma
MachineLearningBlockchainGitHubGatlingWiremock
Data
OraclePL/SQL
DataWarehouseExcelVBA
BigDataJDBC
MongoDB
LastUpdated:November29,2021
ThisTutorialCoversDepthFirstSearch(DFS)inC++inWhichAGraphorTreeisTraversedDepthwise.YouwillAlsoLearnDFSAlgorithm&Implementation:
Depth-firstsearch(DFS)isyetanothertechniqueusedtotraverseatreeoragraph.
DFSstartswitharootnodeorastartnodeandthenexplorestheadjacentnodesofthecurrentnodebygoingdeeperintothegraphoratree.ThismeansthatinDFSthenodesareexploreddepth-wiseuntilanodewithnochildrenisencountered.
Oncetheleafnodeisreached,DFSbacktracksandstartsexploringsomemorenodesinasimilarfashion.
=> WatchOutTheBeginnersC++TrainingGuideHere.
WhatYouWillLearn:DepthFirstSearch(DFS)InC++DFSAlgorithmTraversalsWithIllustrationsDepth-FirstSearchImplementationRuntimeAnalysisIterativeDFSBFSvsDFSApplicationsOfDFSConclusionRecommendedReading
DepthFirstSearch(DFS)InC++
UnlikeBFSinwhichweexplorethenodesbreadthwise,inDFSweexplorethenodesdepth-wise.InDFSweuseastackdatastructureforstoringthenodesbeingexplored.Theedgesthatleadustounexplorednodesarecalled‘discoveryedges’whiletheedgesleadingtoalreadyvisitednodesarecalled‘blockedges’.
Next,wewillseethealgorithmandpseudo-codefortheDFStechnique.
DFSAlgorithm
Step1:Inserttherootnodeorstartingnodeofatreeoragraphinthestack.
Step2:Popthetopitemfromthestackandaddittothevisitedlist.
Step3:Findalltheadjacentnodesofthenodemarkedvisitedandaddtheonesthatarenotyetvisited,tothestack.
Step4:Repeatsteps2and3untilthestackisempty.
Pseudocode
Thepseudo-codeforDFSisgivenbelow.
Fromtheabovepseudo-code,wenoticethattheDFSalgorithmiscalledrecursivelyoneachvertextoensurethatalltheverticesarevisited.
TraversalsWithIllustrations
LetusnowillustratetheDFStraversalofagraph.Forclaritypurposes,wewillusethesamegraphthatweusedintheBFSillustration.
Let0bethestartingnodeorsourcenode.First,wemarkitasvisitedandaddittothevisitedlist.Thenwepushallitsadjacentnodesinthestack.
Next,wetakeoneoftheadjacentnodestoprocessi.e.thetopofthestackwhichis1.Wemarkitasvisitedbyaddingittothevisitedlist.Nowlookfortheadjacentnodesof1.As0isalreadyinthevisitedlist,weignoreitandwevisit2whichisthetopofthestack.
Next,wemarknode2asvisited.Itsadjacentnode4isaddedtothestack.
Next,wemark4whichisthetopofthestackasvisited.Node4hasonlynode2asitsadjacentwhichisalreadyvisited,henceweignoreit.
Atthisstage,onlynode3ispresentinthestack.Itsadjacentnode0isalreadyvisited,henceweignoreit.Nowwemark3asvisited.
Nowthestackisemptyandthevisitedlistshowsthesequenceofthedepth-firsttraversalofthegivengraph.
Ifweobservethegivengraphandthetraversalsequence,wenoticethatfortheDFSalgorithm,weindeedtraversethegraphdepth-wiseandthenbacktrackitagaintoexplorenewnodes.
Depth-FirstSearchImplementation
Let’simplementtheDFStraversaltechniqueusingC++.
#include
usingnamespacestd;
//graphclassforDFStravesal
classDFSGraph
{
intV;//No.ofvertices
list
visited(V,false);
for(inti=0;i
延伸文章資訊
- 1Graph: Depth-First Search(DFS,深度優先搜尋)
DFSVisit(int vertex, int &time) :利用遞迴函式呼叫,進行 color 、 discover 、 finish 與 predecessor 等資料更新的主要函式。 ...
- 2Depth First Search (DFS) C++ Program To Traverse A Graph ...
BFS vs DFS ; Stands for “Breadth-first search”, Stands for “Depth-first search” ; The nodes are e...
- 3Depth First Search or DFS for a Graph - GeeksforGeeks
Implementation: Below are implementations of simple Depth First Traversal. The C++ implementation...
- 4[演算法] [C++ / Python] 深度優先搜尋Depth-First-Search - Part I
[演算法] [C++ / Python] 深度優先搜尋Depth-First-Search - Part I ... 更新:熱騰騰的Part II 出爐囉! 深度優先搜尋,Depth-First...
- 5Depth First Search (DFS) Algorithm - Programiz
Python, Java and C/C++ Examples