CZ
CalcyZone
Computer Science & Software CalcyZone Calculator

Depth-First Search (DFS) Visualizer

Run depth-first search on your own graph and step through the stack and visit order.

DFS visit order
A โ†’ B โ†’ D โ†’ E โ†’ F โ†’ C
Nodes reached
6
Step 1 / 9

Push A. Stack: [A]

Step-by-step working

  1. Push the start node on a stack.
  2. Pop a node; if unvisited, visit it and push its unvisited neighbours (reverse alphabetical so the smallest is explored first).
  3. Repeat until the stack is empty.

Mathematical Formula

Iterative DFS: push start; while stack not empty: pop u; if unvisited, visit u and push unvisited neighbours (reverse order). Time O(V + E).

Overview & Explanation

DFS explores as deep as possible along each branch before backtracking.

How It Works

  • Edges are undirected; neighbours are explored alphabetically.
  • A stack stores the frontier.
  • Visited nodes are skipped when popped again.

Practical Applications

  • Cycle detection and topological sort.
  • Maze solving.
  • Interview preparation.

Example 1: six-node graph from A

Tree-like with one cycle.

1

Inputs

Edges (e.g. A-B, A-C, B-D): A-B, A-C, B-D, B-E, C-F, E-F ยท Start node: A

= entered
2

Step 1

Push the start node on a stack.

3

Step 2

Pop a node; if unvisited, visit it and push its unvisited neighbours (reverse alphabetical so the smallest is explored first).

4

Step 3

Repeat until the stack is empty.

5

DFS visit order

Result

= A โ†’ B โ†’ D โ†’ E โ†’ F โ†’ C

Example 2: square with diagonal from 1

Numeric node names.

1

Inputs

Edges (e.g. A-B, A-C, B-D): 1-2, 2-3, 3-4, 4-1, 1-3 ยท Start node: 1

= entered
2

Step 1

Push the start node on a stack.

3

Step 2

Pop a node; if unvisited, visit it and push its unvisited neighbours (reverse alphabetical so the smallest is explored first).

4

Step 3

Repeat until the stack is empty.

5

DFS visit order

Result

= 1 โ†’ 2 โ†’ 3 โ†’ 4

How it's calculated & sources

Iterative DFS: push start; while stack not empty: pop u; if unvisited, visit u and push unvisited neighbours (reverse order). Time O(V + E).

Frequently Asked Questions

DFS vs BFS?
BFS explores level by level with a queue (shortest paths in unweighted graphs); DFS goes deep with a stack.
Recursive vs iterative?
Both give a valid DFS; the order can differ slightly depending on how neighbours are pushed.
Disconnected graphs?
Only nodes reachable from the start are visited; run again from an unvisited node.