BFS vs DFS: Know the Difference - Guru99

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

There is no need of backtracking in BFS. There is a need of backtracking in DFS. You can never be trapped into finite loops. Skiptocontent WhatisBFS? BFSisanalgorithmthatisusedtographdataorsearchingtreeortraversingstructures.Thealgorithmefficientlyvisitsandmarksallthekeynodesinagraphinanaccuratebreadthwisefashion. Thisalgorithmselectsasinglenode(initialorsourcepoint)inagraphandthenvisitsallthenodesadjacenttotheselectednode.Oncethealgorithmvisitsandmarksthestartingnode,thenitmovestowardsthenearestunvisitednodesandanalysesthem. Oncevisited,allnodesaremarked.Theseiterationscontinueuntilallthenodesofthegraphhavebeensuccessfullyvisitedandmarked.ThefullformofBFSistheBreadth-firstsearch. InthisBSFVs.DFSBinarytreetutorial,youwilllearn: WhatisBFS? WhatisDFS? ExampleofBFS ExampleofDFS DifferencebetweenBFSandDFSBinaryTree ApplicationsofBFS ApplicationsofDFS WhatisDFS? DFSisanalgorithmforfindingortraversinggraphsortreesindepth-warddirection.Theexecutionofthealgorithmbeginsattherootnodeandexploreseachbranchbeforebacktracking.Itusesastackdatastructuretoremember,togetthesubsequentvertex,andtostartasearch,wheneveradead-endappearsinanyiteration.ThefullformofDFSisDepth-firstsearch. ExampleofBFS InthefollowingexampleofDFS,wehaveusedgraphhaving6vertices. ExampleofBFS Step1) Youhaveagraphofsevennumbersrangingfrom0–6. Step2) 0orzerohasbeenmarkedasarootnode. Step3) 0isvisited,marked,andinsertedintothequeuedatastructure. Step4) Remaining0adjacentandunvisitednodesarevisited,marked,andinsertedintothequeue. Step5) Traversingiterationsarerepeateduntilallnodesarevisited. ExampleofDFS InthefollowingexampleofDFS,wehaveusedanundirectedgraphhaving5vertices. Step1) Wehavestartedfromvertex0.Thealgorithmbeginsbyputtingitinthevisitedlistandsimultaneouslyputtingallitsadjacentverticesinthedatastructurecalledstack. Step2) Youwillvisittheelement,whichisatthetopofthestack,forexample,1andgotoitsadjacentnodes.Itisbecause0hasalreadybeenvisited.Therefore,wevisitvertex2. Step3) Vertex2hasanunvisitednearbyvertexin4.Therefore,weaddthatinthestackandvisitit. Step4) Finally,wewillvisitthelastvertex3,itdoesn’thaveanyunvisitedadjoiningnodes.WehavecompletedthetraversalofthegraphusingDFSalgorithm. DifferencebetweenBFSandDFSBinaryTree BFS DFS BFSfindstheshortestpathtothedestination. DFSgoestothebottomofasubtree,thenbacktracks. ThefullformofBFSisBreadth-FirstSearch. ThefullformofDFSisDepthFirstSearch. Itusesaqueuetokeeptrackofthenextlocationtovisit. Itusesastacktokeeptrackofthenextlocationtovisit. BFStraversesaccordingtotreelevel. DFStraversesaccordingtotreedepth. ItisimplementedusingFIFOlist. ItisimplementedusingLIFOlist. ItrequiresmorememoryascomparetoDFS. ItrequireslessmemoryascomparetoBFS. Thisalgorithmgivestheshallowestpathsolution. Thisalgorithmdoesn’tguaranteetheshallowestpathsolution. ThereisnoneedofbacktrackinginBFS. ThereisaneedofbacktrackinginDFS. Youcanneverbetrappedintofiniteloops. Youcanbetrappedintoinfiniteloops. Ifyoudonotfindanygoal,youmayneedtoexpandmanynodesbeforethesolutionisfound. Ifyoudonotfindanygoal,theleafnodebacktrackingmayoccur. ApplicationsofBFS Here,areApplicationsofBFS: Un-weightedGraphs: BFSalgorithmcaneasilycreatetheshortestpathandaminimumspanningtreetovisitalltheverticesofthegraphintheshortesttimepossiblewithhighaccuracy. P2PNetworks: BFScanbeimplementedtolocateallthenearestorneighboringnodesinapeertopeernetwork.Thiswillfindtherequireddatafaster. WebCrawlers: SearchenginesorwebcrawlerscaneasilybuildmultiplelevelsofindexesbyemployingBFS.BFSimplementationstartsfromthesource,whichisthewebpage,andthenitvisitsallthelinksfromthatsource. NetworkBroadcasting: AbroadcastedpacketisguidedbytheBFSalgorithmtofindandreachallthenodesithastheaddressfor. ApplicationsofDFS HereareImportantapplicationsofDFS: WeightedGraph: Inaweightedgraph,DFSgraphtraversalgeneratestheshortestpathtreeandminimumspanningtree. DetectingaCycleinaGraph: AgraphhasacycleifwefoundabackedgeduringDFS.Therefore,weshouldrunDFSforthegraphandverifyforbackedges. PathFinding: WecanspecializeintheDFSalgorithmtosearchapathbetweentwovertices. TopologicalSorting: It isprimarilyusedforschedulingjobsfromthegivendependenciesamongthegroupofjobs.Incomputerscience,itisusedininstructionscheduling,dataserialization,logicsynthesis,determiningtheorderofcompilationtasks. SearchingStronglyConnectedComponentsofaGraph: ItusedinDFSgraphwhenthereisapathfromeachandeveryvertexinthegraphtootherremainingvertexes. SolvingPuzzleswithOnlyOneSolution: DFSalgorithmcanbeeasilyadaptedtosearchallsolutionstoamazebyincludingnodesontheexistingpathinthevisitedset. KEYDIFFERNCES: BFSfindstheshortestpathtothedestinationwhereasDFSgoestothebottomofasubtree,thenbacktracks. ThefullformofBFSisBreadth-FirstSearchwhilethefullformofDFSisDepthFirstSearch. BFSusesaqueuetokeeptrackofthenextlocationtovisit.whereasDFSusesastacktokeeptrackofthenextlocationtovisit. BFStraversesaccordingtotreelevelwhileDFStraversesaccordingtotreedepth. BFSisimplementedusingFIFOlistontheotherhandDFSisimplementedusingLIFOlist. InBFS,youcanneverbetrappedintofiniteloopswhereasinDFSyoucanbetrappedintoinfiniteloops. YouMightLike: DAATutorial:DesignandAnalysisofAlgorithms ArrayinDataStructure:Whatis,ArraysOperations[Examples] AVLTrees:Rotations,Insertion,DeletionwithC++Example SelectionSort:AlgorithmexplainedwithPythonCodeExample HashTableinDataStructure:PythonExample Postnavigation ReportaBug Previous PrevNextContinue Scrolltotop ToggleMenuClose Searchfor: Search



請為這篇文章評分?