Lesson 19 — DFS traversal
DFS: go deep, then backtrack
Depth-first search (DFS) follows one path as far as it can before backing up and trying the next branch. The easiest way to write it is recursion: visit a node, then call dfs on each unvisited neighbour. A seen set prevents loops.
def explore(room):
visited.add(room)
for door in rooms[room]:
if door not in visited:
explore(door)
Why it matters: DFS finds cycles, solves mazes, and works out the order to install software dependencies.
Inside the loop, call dfs on every neighbour that is not in seen yet. Expected order: A, B, D, E, C, F.
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
A quick 3-question quiz on this lesson — instant feedback.
Ready for more? Optional paid resources that pick up where this lesson leaves off.
Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.
Project-based Data Structures courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for Data Structures books — check the publication year so the examples match current versions.
Search Amazon →