Advanced · Module 13 · Lesson 3 of 5
Depth-first search
Depth-first search follows one path as far as it can, then backs up and tries the next. It is the natural way to flood a region, explore every possibility, or ask what is reachable, as long as you watch its depth.
By the end you can
- Run depth-first search recursively and with an explicit stack
- Flood-fill regions of a grid and count connected regions
- Choose between DFS and BFS, and avoid stack overflow on deep searches
Builds on Breadth-first search.
01 · A question first
How many islands are on a map of land and water? Each time you step onto land you haven't seen, flood outward until no land is left, and you have found one whole island. Which order of exploration makes that flood the simplest to write?
Make a guess before you read on.
02 · The idea
Members only
Unlock the full lesson
This lesson is part of the membership. Join to read it in full, along with every other premium deep dive.
What's inside
- Deep before wide
- Flood fill
- The explicit stack
- Which search?
- Recursive and iterative orders differ
- Timestamps
- What DFS knows that BFS doesn't
- Pseudocode & Multi-Language Implementations (C++, Java, Python)
03 · Practice
Asked in interviews
Something wrong with this lesson? Report a problem