Depth First Search (DFS) C++ Program To Traverse A Graph ...

文章推薦指數: 80 %
投票人數:10人

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 #include usingnamespacestd; //graphclassforDFStravesal classDFSGraph { intV;//No.ofvertices list*adjList;//adjacencylist voidDFS_util(intv,boolvisited[]);//AfunctionusedbyDFS public: //classConstructor DFSGraph(intV) { this->V=V; adjList=newlist[V]; } //functiontoaddanedgetograph voidaddEdge(intv,intw){ adjList[v].push_back(w);//Addwtov’slist. } voidDFS();//DFStraversalfunction }; voidDFSGraph::DFS_util(intv,boolvisited[]) { //currentnodevisvisited visited[v]=true; cout<::iteratori; for(i=adjList[v].begin();i!=adjList[v].end();++i) if(!visited[*i]) DFS_util(*i,visited); } //DFStraversal voidDFSGraph::DFS() { //initiallynoneoftheverticesarevisited bool*visited=newbool[V]; for(inti=0;i usingnamespacestd; //graphclass classGraph { intV;//No.ofvertices list*adjList;//adjacencylists public: Graph(intV)//graphConstructor { this->V=V; adjList=newlist[V]; } voidaddEdge(intv,intw)//addanedgetograph { adjList[v].push_back(w);//Addwtov’slist. } voidDFS();//DFStraversal //utilityfunctioncalledbyDFS voidDFSUtil(ints,vector&visited); }; //traversesallnotvisitedverticesreachablefromstartnodes voidGraph::DFSUtil(ints,vector&visited) { //stackforDFS stackdfsstack; //currentsourcenodeinsidestack dfsstack.push(s); while(!dfsstack.empty()) { //Popavertex s=dfsstack.top(); dfsstack.pop(); //displaytheitemornodeonlyifitsnotvisited if(!visited[s]) { cout<visited(V,false); for(inti=0;i SeeHereToExploreTheFullC++Tutorialslist. RecommendedReading BreadthFirstSearch(BFS)C++ProgramtoTraverseaGraphOrTree BinarySearchTreeC++:BSTImplementationAndOperationsWithExamples BTreeAndB+TreeDataStructureInC++ In-DepthEclipseTutorialsForBeginners BinaryTreeDataStructureInC++ GraphImplementationInC++UsingAdjacencyList AVLTreeAndHeapDataStructureInC++ 12BestLineGraphMakerToolsForCreatingStunningLineGraphs[2022RANKINGS] AboutSoftwareTestingHelpHelpingourcommunitysince2006! MostpopularportalforSoftwareprofessionalswith100million+visitsand300,000+followers!YouwillabsolutelyloveourtutorialsonQATesting,Development,SoftwareToolsandServicesReviewsandmore! RecommendedReading BreadthFirstSearch(BFS)C++ProgramtoTraverseaGraphOrTree BinarySearchTreeC++:BSTImplementationAndOperationsWithExamples BTreeAndB+TreeDataStructureInC++ In-DepthEclipseTutorialsForBeginners BinaryTreeDataStructureInC++ GraphImplementationInC++UsingAdjacencyList AVLTreeAndHeapDataStructureInC++ 12BestLineGraphMakerToolsForCreatingStunningLineGraphs[2022RANKINGS] JOINOurTeam!



請為這篇文章評分?