Data Structures · Visualization

Graph: DFS

Graph

Depth-First Search explores a graph by going as deep as possible down one path before backtracking: it picks a neighbor, dives into that neighbor's neighbors, and keeps going deeper until it hits a dead end, then backs up and tries the next unexplored option. Time: O(V + E). Space: O(V) for the visited set and recursion/stack (worst case).

Big-O: BFS/DFS visit each vertex and edge once: O(V + E).

Graph: DFS

Graph

Depth-First Search explores a graph by going as deep as possible down one path before backtracking: it picks a neighbor, dives into that neighbor's neighbors, and keeps going deeper until it hits a dead end, then backs up and tries the next unexplored option. It's typically implemented with recursion (using the call stack) or an explicit stack, along with a 'visited' set.

How DFS Works

  1. Start at a chosen node and mark it visited.
  2. Process the current node.
  3. For each unvisited neighbor, recursively perform DFS from that neighbor.
  4. When a node has no unvisited neighbors left, backtrack to the previous node and continue with its remaining neighbors.

DFS Worked Example

Input: DFS from A in graph A-B, A-C, B-D

  1. Visit A, go to neighbor B
  2. Visit B, go to neighbor D
  3. Visit D, no unvisited neighbors, backtrack to B
  4. B has no more unvisited neighbors, backtrack to A
  5. A goes to neighbor C, visit C

Output: Visit order: A, B, D, C

Graph: Introduction
A set of nodes connected by edges — edges can be one-way or two-way, and optionally carry a weight (cost/distance).
A
B
C
D
E
Unvisited Visited / discovered Current Start
Graph: Introduction
Press ▶ Run to watch it step by step.
Python · Graphs in Code
def dfs(graph, start):
    seen = {start}
    stack = [start]        # stack = dive deep
    while stack:
        v = stack.pop()
        print(v, end=" ")
        for nxt in reversed(graph[v]):
            if nxt not in seen:
                seen.add(nxt)
                stack.append(nxt)

# Recursive version:
# def dfs_rec(v):
#     seen.add(v)
#     for n in graph[v]:
#         if n not in seen:
#             dfs_rec(n)
# example: DFS from
Input: DFS from A in graph A-B, A-C, B-D

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

DFS Time & Space Complexity

TimeO(V + E)
SpaceO(V) for the visited set and recursion/stack (worst case)

When to Use DFS

  • Detecting cycles in a graph
  • Topological sorting of dependency graphs
  • Solving mazes and puzzles (exploring all paths)
  • Finding connected components

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.