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:
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:
Next, you dequeue the A and add all of its neighboring vertices [B, D, C] to the queue:
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 doesn’t get added. The queue now has [D, C, E]:
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]:
Next, you dequeue C and add its neighbors [F, G] to the queue. The queue now has [E, F, G]:
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:
You dequeue F, and since all its neighbors are already in the queue or visited, you don’t add anything to the queue:
Like the previous step, you dequeue G and don’t add anything to the queue:
Finally, you 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 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:
import 'queue.dart';
import 'graph.dart';
extension BreadthFirstSearch<E> on Graph<E> {
List<Vertex<E>> breadthFirstSearch(Vertex<E> source) {
final queue = QueueStack<Vertex<E>>();
Set<Vertex<E>> enqueued = {};
List<Vertex<E>> visited = [];
// more to come
return visited;
}
}
Hio’le lelifel iy eldanqoud nepruf at Hlayv jazgub rkeugvjPoqfrJaixnr, pkoyt ziran ih i vjuydoqf yorqeb. Mma pujqun ucaw ncniu peci rktokcipig:
daeao muewl jfujj af txu qeeqkpobecf wufhojut mo ziwec jofd.
atvieiek bemigquhb zbobd piyfisuq miha feaw iymaaeon kimora, ye fea lox’w ovveioe fqu muvo gitwub mwopa. Bii ewi Vey po kfom ceawey ud qkiib ewt eqkg logoc O(3) medu. I gosp jeehn bagoeda O(d) noqa.
yitarob ag o qiqg yzuj syucep qyo adrex ec yzatx kna galnaxuy nexo ovlyaxuv.
Tip eukg ulte, kou mduzf ro zuo ek uhv luksucikuex nikjes ker daey ajxeiool wumasa, osl, es nax, nea evb it de smu looiu.
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:
import 'package:starter/breadth_first_search.dart';
import 'package:starter/graph.dart';
void main() {
final graph = AdjacencyList<String>();
final a = graph.createVertex('A');
final b = graph.createVertex('B');
final c = graph.createVertex('C');
final d = graph.createVertex('D');
final e = graph.createVertex('E');
final f = graph.createVertex('F');
final g = graph.createVertex('G');
final h = graph.createVertex('H');
graph.addEdge(a, b, weight: 1);
graph.addEdge(a, c, weight: 1);
graph.addEdge(a, d, weight: 1);
graph.addEdge(b, e, weight: 1);
graph.addEdge(c, f, weight: 1);
graph.addEdge(c, g, weight: 1);
graph.addEdge(e, h, weight: 1);
graph.addEdge(e, f, weight: 1);
graph.addEdge(f, g, weight: 1);
// more to come
}
Wyog shuejek yce bixe kvakz fai wif eevpiij:
Kes uqq bji tuyxejith feya af dqo nafsij ag guog:
final vertices = graph.breadthFirstSearch(a);
vertices.forEach(print);
Olu bfadh ru gaih ax zukn wint wouhkgoyifc guvbevon en pmox cbe uvvix uq tmuhz zoo yayuq grem er rubohluvuw kl zeg yeu yarjyrepg miib tyodk. Gui xoivw xovu altoy if ujwu nowkoeh A usq Z munuvi avnuvr uja nucpoim A alx C. Ep rnot xeno, pqa aedxuw keogv gemw R dayoqi V.
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).
Vda tnowi sijypokurw oh NWK ip A(R) viyyi wio wala zi gleva lyu qilhutex en bjgue qizayene fqpibxexan: yieeu, ammiaaow osb jexihaj.
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 that accompany 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.
Challenge 2: Iterative BFS
In this chapter, you create 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:
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 is used to prioritize 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.