β BFS / DFS / A* are limited to N β€ 8. Use Recursive for larger N.
SpeedMed
h(n) heuristic
h=0/N=0
0
Moves
7
Optimal
0
Nodes
0.0s
Time
Result
Tower of Hanoi is a classic AI search problem. Each game state is a node in a 3α΄Ί state graph. Algorithms explore this graph from the initial state to the goal, with different trade-offs in time, memory, and solution quality.
BFS uses a FIFO queue to explore all states at depth d before d+1. Guarantees the shortest-path (optimal) solution, but stores the entire frontier in memory β O(3α΄Ί) space for Hanoi.
Time
O(3βΏ)
Space
O(3βΏ)
Complete?
Yes
Optimal?
Yes
queue β [start]; visited β {start}
while queue β β :
s β queue.dequeue() // FIFO β level by level
if s == goal: returnpath(s)
for s' inexpand(s):
if s' β visited: visited βͺ= s'; queue.add(s')
DFS uses a LIFO stack, diving as deep as possible before backtracking. Memory-efficient at O(n) stack depth, but may find a sub-optimal path depending on the order successors are explored.
Time
O(3βΏ)
Space
O(n)
Complete?
Yes*
Optimal?
No
stack β [start]; visited β {start}
while stack β β :
s β stack.pop() // LIFO β deepest branch first
if s == goal: returnpath(s)
for s' inexpand(s):
if s' β visited: visited βͺ= s'; stack.push(s')
A* uses f(n)=g(n)+h(n) to guide the search. g(n) = cost so far (moves made). h(n) = admissible heuristic: disks not yet correctly stacked from the bottom of Rod C. With admissible h, A* is optimally efficient.
g(n)
Moves made
h(n)
Admissible β
f(n)
g + h
Optimal?
Yes
// h(n) = N β (disks correctly stacked at bottom of C)
open β MinHeap(start, f = 0 + h(start))
while open β β :
n β open.pop_min_f()
if n == goal: return path
for m inexpand(n):
g' β n.g+1; if g' < g[m]: open.push(m, g'+h(m))
State
3-tuple (A,B,C) β each rod = ordered stack, largest disk at bottom
Move(iβj): top of rod i to rod j, if top[i] < top[j] or j is empty
Cost
Uniform β each legal move costs exactly 1
|States|
3α΄Ί reachable states (e.g. 59,049 for N=10)
Live State
Rod A
β
Rod B
β
Rod C
β
Algorithm
Time
Space
Moves
Optimal
Recursive
O(2βΏ)
O(n)
2βΏβ1
Yes β
BFS
O(3βΏ)
O(3βΏ)
2βΏβ1
Yes β
DFS
O(3βΏ)
O(n)
varies
No β
A*
O(3βΏ)*
O(3βΏ)
2βΏβ1
Yes β
* A* explores fewer nodes than BFS thanks to the heuristic, but worst-case is still O(3βΏ). Recursive is uniquely efficient: O(2βΏ) time with only O(n) stack space β the gold standard.
Move Log 0 moves
No moves yet. Tap a rod or hit AI Solve.
β Algorithm Comparison
Computingβ¦
* DFS may find a sub-optimal (longer) path. BFS, A*, and Recursive all find the optimal 2βΏβ1 solution. A* explores fewer nodes than BFS using its admissible heuristic. Recursive uses O(n) stack space vs O(3βΏ) for BFS/A*.