Python Algorithms

Depth-First Search in Python

Depth-first search follows one branch as far as possible before returning to explore another branch.

What is Depth-First Search?

Depth-first search follows one branch as far as possible before returning to explore another branch.

Traverse a graph recursively with depth-first search.

When should you use it?

  • Practice problem solving and data structures.
  • Process data when every algorithm step must be explicit.
  • Prepare for programming exercises, exams, and interviews.

Depth-First Search in Python visualizer

O(V + E)

Use Play or Step to follow each comparison and data movement.

Example code

Run code →
main.py
graph = {"A": ["B", "C"], "B": ["D"], "C": ["E"], "D": [], "E": []}

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

print(depth_first("A"))

Expected output

['A', 'B', 'D', 'C', 'E']

How it works

The visited set prevents repeated work and cycles. Recursive calls act as the traversal stack. Complexity is O(V + E).

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Try empty, single-item, and duplicate-value inputs.
  2. Print state after every step to observe the algorithm.
  3. Benchmark 100, 1,000, and 10,000 items, then compare another approach.
Run in Python IDE →