All topics
89

Depth-first search: go deep, then back up

Tier 1Locked

Where it runs

1. The problem

In the last lesson you used BFS. BFS walks a graph (a set of dots joined by lines) in rings: first the start dot, then every dot one step away, then every dot two steps away. It spreads outward with a queue (a waiting line where the first one in is the first one out). Use it when you want the nearest dots first.

Depth-first search walks the same graph in another way. It does not spread in rings. You pick one path and follow it all the way to a dead end. Then you go back to the last fork and try the next branch. You still reach every dot you can; only the order is different.

You want the same two things as with BFS: reach every dot you can from the start, and do not go in circles when the lines loop back. This lesson answers one question: in what order do the dots come out when you go deep instead of wide?

This step is part of the paid track

The first 33 steps are open to everyone: lesson, exercise and tests. This one opens with full access. Start with a free account and the free steps.

Create a free accountSee what is included

On LeetCode

Graph problems that walk every path or must finish a whole branch before moving on. DFS goes as deep as it can, marks nodes as visited, and backs up to try the next neighbour.

We use necessary cookies to run the site (sign-in and language). If you accept, we also load Google Analytics to see which pages are used, and Google reCAPTCHA to keep spam off the contact and bug-report forms. Privacy policy