Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Data Structures and Algorithms
  • What a Data Structure Is, and How Memory Works
  • Arrays and Dynamic Arrays: Full? Get a Box Twice the Size
  • Linked Lists: A Chain of Clues, Built in Python
  • Stacks: Last In, First Out, With the Undo Button
  • Queues: First In, First Out, With a Ring of Cells
  • Hash Tables: The Name Tells You Where to Look
  • Binary Search Trees: Smaller Left, Bigger Right, Half Gone at Every Look
  • Tree Traversals: In-Order, Pre-Order and Post-Order as a Tour of the House
  • Heaps and Priority Queues: Most Urgent First, Without Searching the Room
  • Graphs and Breadth-First Search (BFS): Fewest Hops, Level by Level
  • Big-O: Reading Cost From Code, With Handshakes and a Guest Book
  • Recursion: Russian Dolls, the Base Case and the Call Stack
  • Linear vs Binary Search: Page by Page, or Open in the Middle
  • Insertion Sort: Take the Next Card and Slide It Left Until It Fits
  • Merge Sort: Split the Pile, Then Merge Two Sorted Piles
  • Quick Sort: Line Up Around One Friend, Then Repeat on Each Side
  • Depth-First Search (DFS): Go Deep, Back Up, Mark Where You've Been
  • The Two Pointers Technique: Find a Pair in One Pass Instead of Every Pair
  • The Sliding Window Technique: One In, One Out
  • Greedy Algorithms: The Best-Looking Choice, Right Now
  • Dynamic Programming: Work It Out Once, Write It Down, Read It Back
  1. Blog
  2. /
  3. Data Structures and Algorithms
  4. /
  5. Algorithms

Depth-First Search (DFS): Go Deep, Back Up, Mark Where You've Been

Depth-first search walks a graph like a maze: follow one corridor as far as it goes, step back at a dead end, and chalk a tick in every room. Emma's friend network step by step, the recursive Python walk, and why a row of ten thousand people crashes it.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Algorithms

What you will learn

  • Explain how DFS goes as deep as it can and backs up at a dead end
  • Write a recursive DFS with a visited set, and say why the set is needed
  • Explain why a very deep graph causes a RecursionError
  • Compare DFS with BFS: same O(V + E) cost, different order and uses

Before you start

  • Graphs as adjacency lists and BFS
  • Recursion and the call stack

These are Emma's friends again, the same six people as in graphs and breadth-first search. Emma knows Jack and Tom. Jack knows Kate and Tom. Tom knows Lucy, who knows Mark. This time we walk differently. Follow one friend, then that friend's friend, then theirs, as deep as you can. Stuck? Step back one friend and try the next one. Going deep first is called depth-first search, or DFS.

Walking a maze

Imagine a maze. The rooms are joined by corridors, and we start in room Emma. We walk deep: Emma, then Jack, then Kate. Kate's room is a dead end, so we walk back to Jack and try his next corridor: Tom, then Lucy, then Mark.

One more trick: we chalk a tick in every room we visit. Emma, Jack and Tom make a loop, and without the ticks we'd go round and round forever. In Python, going deeper means calling the function again, backing up means returning, and the ticks are a visited set.

DFS visit order from Emma: 1 Emma, 2 Jack, 3 Kate (dead end, back up to Jack), 4 Tom, 5 Lucy, 6 Mark. The Emma, Jack, Tom loop is broken by the visited ticks. 1 Emma 2 Jack 3 Kate 4 Tom 5 Lucy 6 Mark dead end, back up to Jack deepest point: 4 steps
Deep first: Emma, Jack, Kate, then back to Jack and on through Tom, Lucy, Mark.

DFS in Python

The graph is the same adjacency list as before: one list of friends per person, each friendship added both ways, and of(who) giving a person's friends in the order they were added. Only the walk is new:

show = True
visited = set()


def walk(g, who, depth):
    visited.add(who)
    if show:
        print("  " * depth + "visit " + who)
    for f in g.of(who):
        if f not in visited:
            walk(g, f, depth + 1)  # go deeper
    # no new friend: back up

visited is the chalk ticks. walk marks this person, prints the name with two spaces per level, then, for each friend not visited yet, calls itself one level deeper. When no new friend is left, the function simply ends, and we back up. Python's call stack remembers the way back.

from friends import Friends
import dfs

friends = Friends()
friends.add("Emma", "Jack")
friends.add("Emma", "Tom")
friends.add("Jack", "Kate")
friends.add("Jack", "Tom")
friends.add("Tom", "Lucy")
friends.add("Lucy", "Mark")

dfs.walk(friends, "Emma", 0)
print("people reached: " + str(len(dfs.visited)))
visit Emma
  visit Jack
    visit Kate
    visit Tom
      visit Lucy
        visit Mark
people reached: 6

Tom lines up with Kate. That's because we backed up to Jack in between, and Tom is Jack's next friend at the same depth.

Step by step

Now atWhat happensCall stack (way back)
Emmatick; Jack is new, go deeperEmma
JackEmma ticked, skip; Kate is new, go deeperEmma, Jack
Kateonly friend Jack is ticked: dead end, back upEmma, Jack, Kate
Jacknext friend Tom is new, go deeperEmma, Jack
TomEmma, Jack ticked; Lucy is newEmma, Jack, Tom
LucyTom ticked; Mark is newEmma, Jack, Tom, Lucy
Markonly friend Lucy ticked: dead endEmma, Jack, Tom, Lucy, Mark
back upLucy, Tom, Jack have nothing new; Emma's last friend Tom is tickedempty, done

Why the ticks matter

Without them, look at the loop: Emma to Jack, then Tom, and Tom is a friend of Emma, so back to Emma, and it all starts again. With the ticks, at Tom we see Emma and Jack already ticked, skip them, and go on to Lucy. Before you walk into a room, look for a tick. That's why nobody is visited twice and the walk always ends.

Far too deep

What's the worst case for going deep? A very long row, where everyone knows only the next person.

from friends import Friends
import dfs

dfs.show = False
for n in (100, 500, 10_000):
    chain = Friends()
    for i in range(1, n):  # one long row
        chain.add("user" + str(i - 1), "user" + str(i))
    dfs.visited.clear()
    dfs.walk(chain, "user0", 0)
    print(f"{n:7,d} in a row: reached {len(dfs.visited):,}")

Output, with the long middle of the traceback cut:

    100 in a row: reached 100
    500 in a row: reached 500
Traceback (most recent call last):
  ...
  [Previous line repeated 995 more times]
  ...
RecursionError: maximum recursion depth exceeded

Every step deeper adds one more call waiting on the stack, and calls only leave when we back up. A hundred is fine, five hundred is fine, but ten thousand fills the stack. Think of a pile of waiting jobs with limited room: once it's full, the program gives up. Programs that go very deep keep their own stack instead, for example a deque, and loop instead of calling themselves.

What it costs

StepCost
Check for a tick (in visited)O(1)
Visit every persononce each, O(V)
Check every friendshipfrom both ends, O(E)
Whole DFSO(V + E)
Stack spaceone call per level of depth

That's the same cost as BFS; only the order differs. Six people and six friendships give six visits and twelve checks. A million people with three million friendships give a million visits and six million checks. One more watch-out: DFS reaches everyone, but the way it finds isn't always the shortest. It reaches Mark in four steps (Jack, Tom, Lucy, Mark), but three is possible, straight through Tom. For fewest hops, use BFS.

Where you meet DFS

  • Solving a maze or puzzle: try one way as far as it goes, step back at a dead end.
  • Searching folders: open a folder, then the folder inside it, back up when done.
  • Checking who is connected: walk from one computer and see who you reach. Anyone left out is cut off.
  • Putting jobs in order when some need others done first.

Try it yourself

Start the walk from Mark instead of Emma. Guess the visit order first, then run it and check.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Data Structures and Algorithms · 17 of 21

Previous
Quick Sort: Line Up Around One Friend, Then Repeat on Each Side
Next post
The Two Pointers Technique: Find a Pair in One Pass Instead of Every Pair

Related courses on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Data Structures and Algorithms Concepts: No Coding Needed

How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)

Related posts

Big-O: Reading Cost From Code, With Handshakes and a Guest Book

Big-O asks one question: how do the steps grow when the list grows? Check a school trip sheet for duplicates two ways, handshakes and a guest book, count every step in Python, then grow the list to ten thousand ids and watch 10,000 steps turn into almost 50 million.

Recursion: Russian Dolls, the Base Case and the Call Stack

Recursion means doing the same job on a smaller piece of the problem, and stopping at a base case. Count Emma's Russian dolls with a Python function that calls itself, watch each call wait on the call stack so the answers come back in reverse, then take the base case out and meet RecursionError.

Linear vs Binary Search: Page by Page, or Open in the Middle

Is kite a real word? Page by page takes 11 checks; opening in the middle takes 4. Trace binary search step by step, see a million words answered in 20 checks, and watch it give the wrong answer on an unsorted list.

Insertion Sort: Take the Next Card and Slide It Left Until It Fits

Emma's hand 7, 3, 9, 2, 5 sorted one card at a time in 6 shifts. Trace each card, see why a backwards hand costs the most, why 5,000 shuffled cards need over 6 million shifts, and why a sorted hand needs zero.

On this page

  • Walking a maze
  • DFS in Python
  • Step by step
  • Why the ticks matter
  • Far too deep
  • What it costs
  • Where you meet DFS
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related courses on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Data Structures and Algorithms Concepts: No Coding Needed

How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.