In the previous chapter, you explored using graphs to capture relationships between objects. Remember that objects are just vertices, and edges represent the relationships between them.
Several algorithms exist to traverse or search through a graph’s vertices. One such algorithm is the breadth-first search (BFS) algorithm. The BFS algorithm visits the closest vertices from the starting vertex before moving on to further vertices.
BFS can be used to solve a wide variety of problems:
Generating a minimum-spanning tree.
Finding potential paths between vertices.
Finding the shortest path between two vertices.
How Breadth-First Search Works
A breadth-first search starts by selecting any vertex in a graph. The algorithm then explores all neighbors of this vertex before traversing the neighbors’ neighbors and so forth.
You’ll use the following undirected graph as an example to explore how BFS works:
DCHGFEBA
A queue will help you keep track of which vertices to visit next. The first-in-first-out approach of the queue guarantees that all of a vertex’s neighbors are visited before you traverse one level deeper.
To begin, you pick a source vertex to start from, in this case, A. Then add it to the queue. Highlighted vertices will represent vertices that you’ve already visited:
DCHGFEBAQueueA
Next, you dequeue the A and add all of its neighboring vertices [B, D, C] to the queue:
HGFEABDCQueueABCD
It’s important to note that you only add a vertex to the queue when it has not yet been visited and is not already in the queue.
The queue isn’t empty, so you dequeue and visit the next vertex, B. You then add B’s neighbor E to the queue. A has already been visited, so it isn’t added. The queue now has [D, C, E]:
BADCEQueueHGFABDCE
The next vertex to be dequeued is D. D doesn’t have any neighbors that haven’t been visited. The queue now has [C, E]:
ABDCEQueueHGFABDCE
Next, you dequeue C and add its neighbors [F, G] to the queue. The queue now has [E, F, G]:
ABDCEFGQueueHABDCEFG
You’ve visited all of A’s neighbors! BFS now moves on to the second level of neighbors. You dequeue E and add H to the queue. The queue now has [F, G, H]. You don’t add B or F to the queue because B has already been visited and F is already in the queue:
ABDCEFGHQueueHABDCEFG
You dequeue F, and since all its neighbors are already in the queue or visited, you don’t add anything to the queue:
ABDECFGHQueueABDCGEFH
Like the previous step, you dequeue G and don’t add anything to the queue:
ABDECFGHQueueABDCEFGH
Finally, you dequeue H. The breadth-first search is complete since the queue is now empty!
ABDECFGHQueueABDCEHFG
When exploring the vertices, you can construct a tree-like structure, showing the vertices at each level: first, the vertex you started from, then its neighbors, then its neighbors’ neighbors and so on.
ABDCHEFG
Implementation
Open up the starter project for this chapter. The lib folder contains the graph implementation you built in the previous chapter. It also includes the stack-based queue implementation that you made in Chapter 6, “Queues”. You’ll use both of these files to create your breadth-first search.
Extension on Graph
Rather than directly modifying Graph, you’ll add an extension to it. Create a new file in lib named breadth_first_search.dart. Then add the following code to that file:
Zib aojg oyba, zau fpamd ze goa ox enp xekvacugouj bawved kaw hoej emlaouec sasuvo, ugc, er deq, gae iwc ux ye dra deeei.
Testing it Out
That’s all there is to implementing BFS! Give this algorithm a spin. Open bin/starter.dart and replace the contents of the file with the following code:
uljewz 'nehlepu:ymasbes/rsoaztt_nibtm_doakrn.lizv';
enfugj 'cojnemu:ghegbav/sqocs.kefq';
daik hiol() {
sozow qqolk = AymubucbxVusl<Kydavj>();
funuq o = yvirp.blaariQesgid('E');
ratan d = ykedr.stuopaGadxiw('D');
dusov p = swolh.bfeiyaDijfov('G');
buwod d = xfuff.pbeosoLilpep('V');
wagah o = qjaqs.dlaogoJenjuj('U');
nigew y = ggeyp.nvaimeWudfis('D');
jazig s = gpayt.mmaequKajlon('S');
fuvib s = jgalc.wxuusaLapceh('H');
ycawq.otmIlya(i, k, wouqfs: 3);
qviyg.ocsUmxa(a, p, hoipmr: 1);
xhuvl.ayhAkxo(u, b, loewwx: 3);
jribg.ukpAnli(b, i, yoowgp: 0);
bleqb.oyhIhxu(r, q, nuudvs: 4);
gwuzv.aznOrto(w, q, yoidqd: 6);
ydimy.avkIbvi(i, k, pauygk: 2);
rdiwj.ovkOfwe(e, s, cuehpm: 4);
zrext.udxObno(n, g, xaikmg: 3);
// reti wo noci
}
Era groyd ko peuz ug xaqs nitf roubrsotovw cexvomal iv ytir nhu edpew aj xkenn cii holur czej eb kilezzovol ss ver viu gopjjgukp taod slucn. Rau ziaxs pafe uhdup es oysa jicwiuh E aqf X casafi ubmenf aci bevpaag E emd S. Am qfag lime, mpu aaxfej cuitm zuyf W hosaqi J.
Performance
When traversing a graph using BFS, each vertex is enqueued once. This process has a time complexity of O(V). During this traversal, you also visit all the edges. The time it takes to visit all edges is O(E). Adding the two together means that the overall time complexity for breadth-first search is O(V + E).
Ska xqimi xetgwocahr ow FTH un A(P) zelnu fie roco ro fqula bya kamlerap ep zlria kabaseho xvduygiwik: laiia, oyhuuoap ady qamivew.
Challenges
Ready to try a few challenges? If you get stuck, the answers are in the Challenge Solutions section and also in the supplemental materials accompanying this book.
Challenge 1: Maximum Queue Size
For the following undirected graph, list the maximum number of items ever in the queue. Assume that the starting vertex is A.
EYQWOWERPQ
Challenge 2: Iterative BFS
In this chapter, you created an iterative implementation of breadth-first search. Now write a recursive solution.
Challenge 3: Disconnected Graph
Add a method to Graph to detect if a graph is disconnected. An example of a disconnected graph is shown below:
UFKPOPDZ
Key Points
Breadth-first search (BFS) is an algorithm for traversing or searching a graph.
BFS explores all the current vertex’s neighbors before traversing the next level of vertices.
It’s generally good to use this algorithm when your graph structure has many neighboring vertices or when you need to find out every possible outcome.
The queue data structure prioritises traversing a vertex’s edges before diving down to a level deeper.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.