Breadth-first search - Wikipedia
文章推薦指數: 80 %
Breadth-first search (BFS) is an algorithm for searching a tree data structure for a node ... which explores the node branch as far as possible before backtracking and ... Breadth-firstsearch FromWikipedia,thefreeencyclopedia Jumptonavigation Jumptosearch Algorithmforsearchingthenodesofagraphinorderbytheirhopcountfromastartingnode Thisarticleneedsadditionalcitationsforverification.Pleasehelpimprovethisarticlebyaddingcitationstoreliablesources.Unsourcedmaterialmaybechallengedandremoved.Findsources: "Breadth-firstsearch" – news ·newspapers ·books ·scholar ·JSTOR(April2012)(Learnhowandwhentoremovethistemplatemessage) Breadth-firstsearchOrderinwhichthenodesareexpandedClassSearchalgorithmDatastructureGraphWorst-caseperformance O ( | V | + | E | ) = O ( b d ) {\displaystyleO(|V|+|E|)=O(b^{d})} Worst-casespacecomplexity O ( | V | ) = O ( b d ) {\displaystyleO(|V|)=O(b^{d})} Graphandtreesearchalgorithms α–β A* B* Backtracking Beam Bellman–Ford Best-first Bidirectional Borůvka Branch&bound BFS BritishMuseum D* DFS Dijkstra Edmonds Floyd–Warshall Fringesearch Hillclimbing IDA* Iterativedeepening Johnson Jumppoint Kruskal LexicographicBFS LPA* Prim SMA* Listings Graphalgorithms Searchalgorithms Listofgraphalgorithms Relatedtopics Dynamicprogramming Graphtraversal Treetraversal Searchgames Graphcoloring vte Animatedexampleofabreadth-firstsearch.Black:explored,grey:queuedtobeexploredlateron ToppartofTic-tac-toegametree Breadth-firstsearch(BFS)isanalgorithmforsearchingatreedatastructureforanodethatsatisfiesagivenproperty.Itstartsatthetreerootandexploresallnodesatthepresentdepthpriortomovingontothenodesatthenextdepthlevel.Extramemory,usuallyaqueue,isneededtokeeptrackofthechildnodesthatwereencounteredbutnotyetexplored. Forexample,inachessendgameachessenginemaybuildthegametreefromthecurrentpositionbyapplyingallpossiblemoves,andusebreadth-firstsearchtofindawinpositionforwhite.Implicittrees(suchasgametreesorotherproblem-solvingtrees)maybeofinfinitesize;breadth-firstsearchisguaranteedtofindasolutionnode[1]ifoneexists. Incontrast,(plain)depth-firstsearch,whichexploresthenodebranchasfaraspossiblebeforebacktrackingandexpandingothernodes,[2]maygetlostinaninfinitebranchandnevermakeittothesolutionnode.Iterativedeepeningdepth-firstsearchavoidsthelatterdrawbackatthepriceofexploringthetree'stoppartsoverandoveragain.Ontheotherhand,bothdepth-firstalgorithmsgetalongwithoutextramemory. Breadth-firstsearchcanbegeneralizedtographs,whenthestartnode(sometimesreferredtoasa'searchkey')[3]isexplicitlygiven,andprecautionsaretakenagainstfollowingavertextwice. BFSanditsapplicationinfindingconnectedcomponentsofgraphswereinventedin1945byKonradZuse,inhis(rejected)Ph.D.thesisonthePlankalkülprogramminglanguage,butthiswasnotpublisheduntil1972.[4]Itwasreinventedin1959byEdwardF.Moore,whousedittofindtheshortestpathoutofamaze,[5][6]andlaterdevelopedbyC.Y.Leeintoawireroutingalgorithm(published1961).[7] Contents 1Pseudocode 1.1Moredetails 1.2Example 2Analysis 2.1Timeandspacecomplexity 2.2Completeness 3BFSordering 4Applications 5Seealso 6References 7Externallinks Pseudocode[edit] Input:AgraphGandastartingvertexrootofG Output:Goalstate.Theparentlinkstracetheshortestpathbacktoroot[8] 1procedureBFS(G,root)is 2letQbeaqueue 3labelrootasexplored 4Q.enqueue(root) 5whileQisnotemptydo 6v :=Q.dequeue() 7ifvisthegoalthen 8returnv 9foralledgesfromvtowinG.adjacentEdges(v)do 10ifwisnotlabeledasexploredthen 11labelwasexplored 12Q.enqueue(w) Moredetails[edit] Thisnon-recursiveimplementationissimilartothenon-recursiveimplementationofdepth-firstsearch,butdiffersfromitintwoways: itusesaqueue(FirstInFirstOut)insteadofastackand itcheckswhetheravertexhasbeenexploredbeforeenqueueingthevertexratherthandelayingthischeckuntilthevertexisdequeuedfromthequeue. IfGisatree,replacingthequeueofthisbreadth-firstsearchalgorithmwithastackwillyieldadepth-firstsearchalgorithm.Forgeneralgraphs,replacingthestackoftheiterativedepth-firstsearchimplementationwithaqueuewouldalsoproduceabreadth-firstsearchalgorithm,althoughasomewhatnonstandardone.[9] TheQqueuecontainsthefrontieralongwhichthealgorithmiscurrentlysearching. Nodescanbelabelledasexploredbystoringtheminaset,orbyanattributeoneachnode,dependingontheimplementation. Notethatthewordnodeisusuallyinterchangeablewiththewordvertex. Theparentattributeofeachnodeisusefulforaccessingthenodesinashortestpath,forexamplebybacktrackingfromthedestinationnodeuptothestartingnode,oncetheBFShasbeenrun,andthepredecessorsnodeshavebeenset. Breadth-firstsearchproducesaso-calledbreadthfirsttree.Youcanseehowabreadthfirsttreelooksinthefollowingexample. Example[edit] Thefollowingisanexampleofthebreadth-firsttreeobtainedbyrunningaBFSonGermancitiesstartingfromFrankfurt: AnexamplemapofSouthernGermanywithsomeconnectionsbetweencities Thebreadth-firsttreeobtainedwhenrunningBFSonthegivenmapandstartinginFrankfurt Analysis[edit] Timeandspacecomplexity[edit] Thetimecomplexitycanbeexpressedas O ( | V | + | E | ) {\displaystyleO(|V|+|E|)} ,sinceeveryvertexandeveryedgewillbeexploredintheworstcase. | V | {\displaystyle|V|} isthenumberofverticesand | E | {\displaystyle|E|} isthenumberofedgesinthegraph. Notethat O ( | E | ) {\displaystyleO(|E|)} mayvarybetween O ( 1 ) {\displaystyleO(1)} and O ( | V | 2 ) {\displaystyleO(|V|^{2})} ,dependingonhowsparsetheinputgraphis.[10] Whenthenumberofverticesinthegraphisknownaheadoftime,andadditionaldatastructuresareusedtodeterminewhichverticeshavealreadybeenaddedtothequeue,thespacecomplexitycanbeexpressedas O ( | V | ) {\displaystyleO(|V|)} ,where | V | {\displaystyle|V|} isthenumberofvertices.Thisisinadditiontothespace requiredforthegraphitself,whichmayvarydependingonthegraphrepresentationusedbyanimplementationofthealgorithm. Whenworkingwithgraphsthataretoolargetostoreexplicitly(orinfinite),itismorepracticaltodescribethecomplexityofbreadth-firstsearchindifferentterms:tofindthenodesthatareatdistancedfromthestartnode(measuredinnumberofedgetraversals),BFStakesO(bd+1)timeandmemory,wherebisthe"branchingfactor"ofthegraph(theaverageout-degree).[11]: 81 Completeness[edit] Intheanalysisofalgorithms,theinputtobreadth-firstsearchisassumedtobeafinitegraph,representedexplicitlyasanadjacencylist,adjacencymatrix,orsimilarrepresentation.However,intheapplicationofgraphtraversalmethodsinartificialintelligencetheinputmaybeanimplicitrepresentationofaninfinitegraph.Inthiscontext,asearchmethodisdescribedasbeingcompleteifitisguaranteedtofindagoalstateifoneexists.Breadth-firstsearchiscomplete,butdepth-firstsearchisnot.Whenappliedtoinfinitegraphsrepresentedimplicitly,breadth-firstsearchwilleventuallyfindthegoalstate,butdepthfirstsearchmaygetlostinpartsofthegraphthathavenogoalstateandneverreturn.[12] BFSordering[edit] AnenumerationoftheverticesofagraphissaidtobeaBFSorderingifitisthepossibleoutputoftheapplicationofBFStothisgraph. Let G = ( V , E ) {\displaystyleG=(V,E)} beagraphwith n {\displaystylen} vertices.Recallthat N ( v ) {\displaystyleN(v)} isthesetofneighborsof v {\displaystylev} . Let σ = ( v 1 , … , v m ) {\displaystyle\sigma=(v_{1},\dots,v_{m})} bealistofdistinctelementsof V {\displaystyleV} ,for v ∈ V ∖ { v 1 , … , v m } {\displaystylev\inV\setminus\{v_{1},\dots,v_{m}\}} ,let ν σ ( v ) {\displaystyle\nu_{\sigma}(v)} betheleast i {\displaystylei} suchthat v i {\displaystylev_{i}} isaneighborof v {\displaystylev} ,ifsucha i {\displaystylei} exists,andbe ∞ {\displaystyle\infty} otherwise. Let σ = ( v 1 , … , v n ) {\displaystyle\sigma=(v_{1},\dots,v_{n})} beanenumerationoftheverticesof V {\displaystyleV} . Theenumeration σ {\displaystyle\sigma} issaidtobeaBFSordering(withsource v 1 {\displaystylev_{1}} )if,forall 1 < i ≤ n {\displaystyle1
延伸文章資訊
- 1BFS 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...
- 2Explain BFS and DFS in terms of backtracking - Stack Overflow
Is BFS is possible using backtracking? - Stack Overflow
- 3Breadth-first search - Wikipedia
Breadth-first search (BFS) is an algorithm for searching a tree data structure for a node ... whi...
- 4Day9 -- Brute Force - DFS & BFS - iT 邦幫忙
今天會是最後一天介紹Brute Force類別的演算法,而今天要講的內容是 Depth-First Search(DFS) 和 Breadth-First Search(BFS) ,這兩種演算法...
- 5Backtracking & Branch-and-Bound - Sharon Peng
物品的重量(Weight) · 最大獲利(Maxprofit) · 背包可以承載的重量(W) · 界線(Bound,可以是上界或下界,看題目需求) · 尋訪樹(Tree)時,使用BFS.