Breadth-first search - Wikipedia

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

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



請為這篇文章評分?