Depth-First Search (DFS)
Software Engineer path · lesson 22 of 99Explore graphs by going deep! Unlike BFS, DFS dives into the graph structure. Essential for detecting cycles, topological sort, and maze solving.
Undirected, like A-B, B-C. Badges show discovery/finish times (DFS) or distance (BFS).
Same graph, same start: compare the visit order.
Depth-first from A: go as deep as possible, then backtrack.
- 1dfs(u):
- 2 visited.add(u); disc[u] = time++
- 3 for v in neighbours(u):
- 4 if v not visited: parent[v] = u; dfs(v) # tree edge
- 5 elif v != parent[u]: found a cycle # back edge
- 6 finish[u] = time++ # backtrack
- Visits
- 0 / 6
- Edge checks
- 0 / 12
Tap any element in the diagram to inspect its state at this step.
Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.
Go deep first
Graph: A → B, C · B → D, E · C → F. Visiting neighbours alphabetically, order the nodes as DFS from A visits them.
Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.
- 1Drop a step here
- 2Drop a step here
- 3Drop a step here
- 4Drop a step here
- 5Drop a step here
- 6Drop a step here
Test your knowledge
What data structure is implicitly used in recursive DFS?
Write the code
Number of Islands
function numIslands(grid) {
// Your code here
}When to reach for this
- Find **Connected Components**
- Detect Cycles in a Graph
- Maze solving / Path existence
- Topological Sorting (DFS based)
Interview Questions
References & Further Reading
Love this visualization?
Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.
100% free • No credit card required