Tower of Hanoi
Move n disks from peg A to peg C using peg B. Initially all disks are on A, largest at the bottom and smallest at the top. Move only one top disk at a time,…
Move n disks from peg A to peg C using peg B. Initially all disks are on A, largest at the bottom and smallest at the top. Move only one top disk at a time, and never place a larger disk on a smaller disk. Return the canonical minimum-length sequence as records with exactly disk, from and to. Disk 1 is the smallest. Implement tower_of_hanoi(n) in Python or towerOfHanoi(n) in the other languages. The canonical recurrence moves n-1 disks to the auxiliary peg, moves disk n to the destination, then moves the smaller disks onto it. For zero disks return an empty list.
- n is a strict integer with 0 <= n <= 10; booleans are not disk counts. - Peg names are exactly A, B and C. - Return exactly 2^n - 1 moves in their canonical execution order. - Each record contains only disk (an integer), from and to (distinct peg strings). - C++ Move is platform-owned: struct Move { int disk; string from; string to; }. - Coding supports n through 10. Complete teaching journeys use n through 3.
Example 1: input n = 0; output []. The base case needs no physical move.
Example 2: input n = 1; output [{"disk":1,"from":"A","to":"C"}]. The only disk moves directly to its destination.
Example 3: input n = 2; output [{"disk":1,"from":"A","to":"B"},{"disk":2,"from":"A","to":"C"},{"disk":1,"from":"B","to":"C"}]. Clear disk 2, move it, then restore the smaller disk above it.
Category: Recursion. Topic: recursion. Difficulty: Medium. Patterns: recursion.