Builds onRepresenting a graphRecursion and the call stack
01The idea
Searching a graph means starting at one node and following edges to reach others. There are two ways to do it, and both need something a tree search does not. They need a record of the nodes you have already reached. Graphs can have loops, so without that record the search walks in circles.
Breadth-first search, or BFS, uses a queue. Take a node from the front, look at its neighbours, and put every neighbour you have not reached yet at the back. Nodes come out in order of distance from the start: first the start, then everything one edge away, then everything two edges away. So BFS finds the fewest edges from the start to every node.
Depth-first search, or DFS, follows one path as far as it can, then backs up and tries the next branch. It is written as a recursive function, or as a loop with a stack. DFS does not find shortest paths. It is simpler when you only need to know what is reachable, how many separate groups there are, or whether there is a cycle.
Mark a node as reached when it joins the queue, not when it leaves. Otherwise the same node can join the queue several times, once from each neighbour.
02How to spot it
Use BFS when:
- the question asks for the fewest steps, moves or edges, and every edge counts the same
- you spread out from one or more starting points in rounds, such as rot spreading through a grid or a fire spreading
- you need the nodes in order of distance
Use DFS when:
- you only need to know whether something is reachable
- you count connected groups, such as islands in a grid. Start a search from every unvisited cell and count how many searches you start
- you look for a cycle, or you need to explore every path
Grids are graphs too. Each cell connects to its four neighbours. Use the cell itself as the node, and check that a neighbour is inside the grid before you visit it.
If the edges have different weights, BFS no longer finds the cheapest path. That needs a heap, which is the shortest paths lesson.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue