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 = 02. 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 β F5. 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 0Quick check
Ready for the pattern catalog and interview classics? Head to Patterns or jump straight to Practice Questions.