BFS vs DFS: Know the Difference - Guru99
文章推薦指數: 80 %
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
延伸文章資訊
- 1DFS、BFS和Backtracking模板_Jaylon Wang的专栏 - CSDN博客
DFS和Backtracking的区别Backtracking是一种更通用的算法。深度优先搜索是与搜索树结构相关的特定回溯形式。 来自维基百科:一个从根开始(在图形情况 ...
- 2Backtracking & Branch-and-Bound - Sharon Peng
物品的重量(Weight) · 最大獲利(Maxprofit) · 背包可以承載的重量(W) · 界線(Bound,可以是上界或下界,看題目需求) · 尋訪樹(Tree)時,使用BFS.
- 3Breadth first search with BackTracking. - gists · GitHub
public class BFS{. public static Node[] prev;. public static Graph G;. public static void BFSWith...
- 4What is the relationship among backtracking, breadth-first ...
BFS does not do any backtracking. Other forms of exhaustive search include: enumeration: listing ...
- 5BFS vs DFS: Know the Difference - Guru99
There is no need of backtracking in BFS. There is a need of backtracking in DFS. You can never be...