πŸš€ Phases 1–5 are live β€” Days 1–17 cover the foundations and the algorithmic patterns. See the roadmap β†’

Basic DFS / BFS Questions

Six warm-up drills to lock in the traversal templates before the interview classics. Each one builds on the previous: implement the template, trace by hand, spot the algorithm, then start customizing.

If you can do these without looking up the templates, the practice problems will feel mechanical.

1. Implement DFS from scratch

Given an adjacency list and a starting vertex, return the list of vertices visited in DFS order.

graph = {
    0: [1, 2],
    1: [0, 3],
    2: [0, 4],
    3: [1],
    4: [2],
}
start = 0

2. Implement BFS from scratch

Same graph, same starting vertex β€” return the layer-by-layer order.

3. Find the shortest distance from a source

Given an unweighted adjacency list, return the BFS distance (number of edges) from start to every other vertex. Use -1 for unreachable.

4. Trace BFS layers by hand

For the graph below, what is the BFS layer order starting from A?

A β€” B β€” D
|       |
C β€” E β€” F

5. Spot the right algorithm

For each problem, would you reach for DFS, BFS, or β€œeither works”?

a) Find the shortest sequence of word transformations from "cat" to "dog". b) Determine if there’s any path from city A to city B. c) Find all cycles in a directed graph. d) Count the number of islands in a grid. e) Find the minimum number of steps to escape a maze. f) Generate a topological ordering of tasks with dependencies.

6. Count islands in a grid (mini-version)

Given a 4Γ—4 grid where 1 is land and 0 is water, how many islands? An island is a group of 1s connected horizontally or vertically.

1 1 0 0
1 0 0 1
0 0 1 1
1 0 0 0

Quick check

The only essential difference between iterative DFS and BFS is:
If the graph has 10,000 nodes and 50,000 edges, how many times does BFS visit each node?
You want to find the SHORTEST path from node A to node B in an unweighted graph. Which approach is correct?

Ready for the pattern catalog and interview classics? Head to Patterns or jump straight to Practice Questions.