CarolZander
Breadthfirstsearch
Thebreadthfirstalgorithmvisitsalladjacentnodes(children)beforevisitingtheiradjacentnodes,andsoon. Aswithdepthfirst,whenwevisiteachvertex,wehavetodecideinwhatordertovisittheadjacentvertex. Wewillassumeanunderlyingorderingimpliedbythenodenumber(orindex).Westartatvertex1(or0 dependingonwherewestartcounting)andconsiderasmallernumberednodebeforealargernumbered node.
void breadthFirstSearch(. . .) { // mark all the vertices as not visited for v = 1 to n { if (v is not visited) bfs(v); } } void bfs(v ...){ mark v as visited Q.enqueue(v); while (Q is not empty) { x = Q.dequeue(); output x (or do whatever, output give breadth-first ordering) for each vertex w adjacent to x { if (w is not visited) { mark w as visited Q.enqueue(w); } } } }
Usethesameexample(unconnectedgraph)asusedwithdepthfirst:
10
12
11
Thebreadthfirstorderingis123945867101112.
Page 1 of 2
UsesofBreadthfirstsearch
BreadthfirstTraversingisoftenusedfortheprocessingofdigitalimages.Itpresentsefficientalgorithmsfor eroding,dilating,skeletonizing,anddistancetransformingregions.Thesealgorithmsworkbytraversing regionsinabreadthfirstmanner,usingaqueueforstorageofunprocessedpixels.Theyusememory efficientlypixelsareremovedfromthequeueassoonastheirprocessinghasbeencompletedandthey processonlypixelsintheregion(andtheirneighbors),ratherthanrequiringacompletescanoftheimage. Theimageisstillrepresentedasapixelmatrixinmemory;thegraphisjustaconvenientframeworkfor thinkingaboutthealgorithms. Breadthfirstsearch(BFS)isusedforfindingallconnectedcomponentsinagraph(findingallnodeswithinone connectedcomponent).ThesetofnodesreachedbyaBFSarethelargestconnectedcomponentcontaining thestartnode. AvariationofBFSisusedforfindingtheshortestpathbetweentwonodesuandv(inanunweightedgraph).It isalsousedforfindingtheshortestpathbetweentwonodesuandv(inaweightedgraph).ThisisDijkstras algorithm. BFScanbeusedtotestbipartiteness(whenagraphssetofverticescanbedividedintotwodisjointsetsso thateveryedgeinthegraphconnectsavertexfromonesettotheother,seeSection9.2inthetext).The algorithmstartsthesearchatanyvertexandgivesalternatinglabelstotheverticesvisitedduringthesearch. Thatis,givelabel0tothestartingvertex,1toallitsneighbors,0tothoseneighbors'neighbors,andsoon.Ifat anystepavertexhas(visited)neighborswiththesamelabelasitself,thenthegraphisnotbipartite.Ifthe searchendswithoutsuchasituationoccurring,thenthegraphisbipartite.
UsesofDepthfirstsearch
Abiconnectedgraphisagraphwheretheremovalofnoverticesdisconnectsthegraph.Thisisimportantwith networks.Ifonecomputergoesdown,thenetworkshouldnotbeaffected.Similarlyinamasstransitsystem, thereneedstobealternateroutes.Anarticulationpointisanodewhoseremovalwoulddisconnectthegraph (criticaltoproblemsmentioned).Allarticulationpointsinaconnectedgraphcanbefoundusingdepthfirst search.
Page 2 of 2