🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Depth-First Search (DFS) — Recursion and Stack — Complete Beginner Guide

Data Structures FoundationsDepth-First Search (DFS) — Recursion and Stack🟢 Free Lesson

Depth-First Search (DFS) — Recursion and Stack — Complete Beginner Guide

Learning Objectives

  • Implement recursive DFS on a graph
  • Rewrite DFS with an explicit stack
  • Explain the role of visited and call stacks
  • Contrast DFS path style with BFS waves
  • Analyze time and space for DFS

What Is DFS?

Depth-first search plunges along one branch as far as possible before backtracking. It explores deep paths early instead of finishing an entire level first.

Recursion mirrors the backtracking naturally because the call stack remembers where to return.

python
def dfs_recursive(graph, node, visited=None):
    if visited is None:
        visited = set()
    visited.add(node)
    order = [node]
    for neighbor in graph[node]:
        if neighbor not in visited:
            order.extend(dfs_recursive(graph, neighbor, visited))
    return order


graph = {
    "A": ["B", "C"],
    "B": ["A", "D", "E"],
    "C": ["A", "F"],
    "D": ["B"],
    "E": ["B", "F"],
    "F": ["C", "E"],
}

print(dfs_recursive(graph, "A"))

Recursive DFS Anatomy

Every recursive solution needs two pieces.

PiecePurpose
Base caseStop when node visited or leaf reached
Recursive caseVisit one unvisited neighbor deeper

The visited set stops infinite loops on cyclic graphs.

Traversal Skeleton

python
def dfs_visit(graph, node, visited, out):
    if node in visited:
        return
    visited.add(node)
    out.append(node)
    for neighbor in graph[node]:
        dfs_visit(graph, neighbor, visited, out)

Iterative DFS with an Explicit Stack

The system call stack works, but deep graphs can overflow it. An explicit stack puts control in your hands.

python
def dfs_iterative(graph, start):
    visited = set()
    stack = [start]
    order = []
    while stack:
        node = stack.pop()
        if node in visited:
            continue
        visited.add(node)
        order.append(node)
        # Reverse neighbors so leftmost explores first
        for neighbor in reversed(graph[node]):
            if neighbor not in visited:
                stack.append(neighbor)
    return order


print(dfs_iterative(graph, "A"))

Pushing neighbors in reverse keeps the same left-to-right order as the recursive version.

Recursion Stack versus Data Stack

StackHoldsGrowth
Call stackFrames of active callsDepth of recursion
Explicit DFS stackNodes waiting to expandPath length and branches
BFS queueNodes waiting to expandWidth of current level

Deep narrow graphs stress the call stack. Wide graphs stress the BFS queue.

DFS for Paths and Cycles

DFS is natural for reachability, topological sort, connected components, and cycle detection.

python
def find_path(graph, start, goal, visited=None, path=None):
    if visited is None:
        visited = set()
    if path is None:
        path = []
    visited.add(start)
    path = path + [start]
    if start == goal:
        return path
    for neighbor in graph[start]:
        if neighbor not in visited:
            result = find_path(graph, neighbor, goal, visited, path)
            if result is not None:
                return result
    return None


print(find_path(graph, "A", "F"))

Note that a DFS path is not guaranteed to be the shortest. Use BFS for fewest edges.

Complexity

MetricCostNotes
Time adjacency listO(V plus E)Each vertex and edge once
Time adjacency matrixO(V squared)Row scans
Space visitedO(V)Tracks processed nodes
Space stackO(h) to O(V)Follows path depth

BFS versus DFS

CriteriaBFSDFS
FrontierQueueStack or recursion
PriorityShallow firstDeep first
Shortest unweighted pathYesNot always
Memory on wide graphsHighLower
Typical usesLevels, hopsCycles, topo sort, components

DFS Dry Runs and Cycle Ideas

Trace recursive DFS with an explicit stack drawing. Push the start node, pop it, mark it, then push neighbors so the first neighbor expands next. Keep a call stack column beside the data stack column to see how recursion mirrors iteration.

For cycle detection on an undirected graph, a visited neighbor that is not the immediate parent means a cycle. For directed graphs, track nodes on the current recursion path; revisiting a node still on that path closes a cycle.

ContextCycle Signal
UndirectedNeighbor visited and not parent
Directed recursionNeighbor on current path stack
Union-find componentsUnion joins already connected ends

Practice both flavors on a six-node graph with one deliberate cycle. If your code misses it, check whether you mark visited too late or ignore the parent rule. DFS subtleties hide in those two details more often than anywhere else.

Key Takeaways

💡

  • DFS dives deep and backtracks instead of sweeping levels
  • Recursion uses the call stack; iterative DFS uses your own stack
  • Visited sets are required on graphs with cycles
  • DFS time is O(V plus E) on adjacency lists
  • Prefer BFS for shortest hop paths and DFS for structure probes

Practice Questions

  1. Rewrite the recursive DFS using an explicit stack and explain neighbor push order.
  2. Why can recursion overflow on a graph shaped like a long path?
  3. Give one task where DFS is clearly better than BFS and justify your choice.

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Data Structures Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement