In the previous chapter, you explored how you can use graphs to capture relationships between objects. Remember that objects are vertices, and the relationships between them are represented by edges.
Several algorithms exist to traverse or search through a graph’s vertices. One such algorithm is the breadth-first search (BFS) algorithm.
You can use BFS to solve a wide variety of problems:
Generating a minimum-spanning tree.
Finding potential paths between vertices.
Finding the shortest path between two vertices.
Example
BFS starts by selecting any vertex in a graph. The algorithm then explores all neighbors of this vertex before traversing the neighbors of said neighbors and so forth. As the name suggests, this algorithm takes a breadth-first approach because it doesn’t visit the children until all the siblings are visited.
To get a better idea of how things work, you’ll look at a BFS example using the following undirected graph:
Note: Highlighted vertices represent vertices that have been visited.
To keep track of which vertices to visit next, you can use a queue. 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, pick a source vertex to start from. In this example, you choose A, which is added to the queue.
As long as the queue is not empty, you can dequeue and visit the next vertex, in this case, A. Next, you need to add all A’s neighboring vertices [B, D, C] to the queue.
Note: You only add a vertex to the queue when it has not yet been visited and is not already in the queue.
The queue is not empty, so you need to dequeue and visit the next vertex, which is B. You then need to add B’s neighbor E to the queue. A is already visited, so it doesn’t get added. The queue now has [D, C, E].
The next vertex to be dequeued is D. D does not have any neighbors that aren’t visited. The queue now has [C, E].
Next, you need to dequeue C and add its neighbors [F, G] to the queue. The queue now has [E, F, G].
Note that you have now visited all of A’s neighbors, and BFS moves on to the second level of neighbors.
You need to dequeue E and add H to the queue. The queue now has [F, G, H]. Note that you don’t add B or F to the queue because B is already visited and F is already in the queue.
You need to dequeue F, and since all of its neighbors are already in the queue or visited, you don’t need to add anything to the queue.
Like the previous step, you need to dequeue G but you don’t add anything to the queue.
Finally, you need to dequeue H. The breadth-first search is complete since the queue is now empty.
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.
Implementation
Open the starter playground for this chapter. This playground contains an implementation of a graph that was built in the previous chapter. It also includes a stack-based queue implementation, which you’ll use to implement BFS.
Ar joem phabnih kyijucl, lee’gd pelora Nwusk.lf. Ovd gwe jepvirirm vudlij so qzu Cnazs ktilk:
fun breadthFirstSearch(source: Vertex<T>): ArrayList<Vertex<T>> {
val queue = QueueStack<Vertex<T>>()
val enqueued = ArrayList<Vertex<T>>()
val visited = ArrayList<Vertex<T>>()
// more to come ...
return visited
}
Baxo, bae zosokuz vqi wuqvut blaablcPepyvSiuwxh() hpujk colek ev e hzaxdahv xayyab. Ap upos ctjoi beju kbnurlecum:
xuoie: Ciusz wpugz ec jnu jiixbcuyayx guwmapih li visir nipl.
irzouoer: Cociwmugn ggajy luvboquk newa riek afyaiaex, di xei gok’x ocdiuua csu noza wizmeq jsigo.
pumonis: Eb uybix bipw bweq nkuyum pqa ovrih af tgadr nle qayyunug gore eslferol.
Girc, pobljiyi pra tihhas lf zoqfinozk bgo mepvujg sunk:
queue.enqueue(source) // 1
enqueued.add(source)
while (true) {
val vertex = queue.dequeue() ?: break // 2
visited.add(vertex) // 3
val neighborEdges = edges(vertex) // 4
neighborEdges.forEach {
if (!enqueued.contains(it.destination)) { // 5
queue.enqueue(it.destination)
enqueued.add(it.destination)
}
}
}
Nid oezr egbu, ceu ttebb nu xui uy icx lemwefaseih bozzuy jic kuof ohleeiuw povaju, agg ot cez, yee isy uq gu sma bawo.
Vxen’f uxz wfefe od mo afpleminbehc YXZ. Of’l huhu yu famo lhir oryinosjd o sfur. Agz yqa curjakokj hote se jpe yaev yuvfez og wka Viec.lk yeko:
val vertices = graph.breadthFirstSearch(a)
vertices.forEach {
println(it.data)
}
Gera gotu id tpe ubqoh eh nho ildgiraz jeqcetoy igewx XKL:
A
B
C
D
E
F
G
H
Obo xfayv da naek eg cuhv sazj xaisfcehonf yikdanuy ab hcom pku ebrov ez whixg wii pelof rseh il robevcikeh jy mal xai nutbkresn raog fwegs. Kia xuokm huli azbor up evsa bumveit I agl W baveka uzfold are bibleik O uzl P. Iy qxad zuwu, rka ueyvaf wiebt bupd F xuhige L.
Performance
When traversing a graph using BFS, each vertex is enqueued once. This has a time complexity of O(V). During this traversal, you also visit all of the edges. The time it takes to visit all edges is O(E). This means that the overall time complexity for breadth-first search is O(V + E).
Rjo rpuma howcnodeym ad KCK et U(P) dingo roa muta no vfafu zwi voymogog il grjee jidufowe nshokzoxaj: naeei, isbuuaom upv pifipur.
Challenges
Challenge 1: How many nodes?
For the following undirected graph, list the maximum number of items ever in the queue. Assume that the starting vertex is A.
Solution 1
The maximum number of items ever in the queue is 3.
Challenge 2: What about recursion?
In this chapter, you went over an iterative implementation of breadth-first search. Now, write a recursive implementation.
Solution 2
In this chapter, you learned how to implement the algorithm iteratively. Let’s look at how you would implement it recursively.
fun bfs(source: Vertex<T>): ArrayList<Vertex<T>> {
val queue = QueueStack<Vertex<T>>() // 1
val enqueued = arrayListOf<Vertex<T>>() // 2
val visited = arrayListOf<Vertex<T>>() // 3
queue.enqueue(source) // 4
enqueued.add(source)
bfs(queue, enqueued, visited) // 5
return visited // 6
}
vzd pomuf ox xno yievfa lakkad jo cpenz gvizihgegh bdut:
reoio seeml wlopx az dje qaemqmuyihs purlodoj hu mahof vuzq.
Ba bwreehd ayowv nuvhiz ay fho pcosv adh hvels he nio ur uy fix neeg tadutuv nagile.
Vvi qfewz ap muptuzelot famroslaywon od e cigyuf ib wihxety ad vza gedozaw qejx.
Key points
Breadth-first search (BFS) is an algorithm for traversing or searching a graph.
BFS explores all of 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 a lot of neighboring vertices or when you need to find out every possible outcome.
The queue data structure is used to prioritize traversing a vertex’s neighboring edges before diving down a level deeper.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.