All tasks
Hardrecursion

Tower of Hanoi

Time limit 2 s · Memory 64 MBAcceptance: 100.0%Solved by: 1

Statement

There are pegs A, B, C, with n disks on peg A (a larger disk may never sit on a smaller one). Move all disks to peg C using the minimum number of moves. Print the number of moves on the first line, then each move on its own line as "X Y" (from peg X to peg Y). Follow the standard order: first move n-1 disks to the helper peg, then the largest disk, then the n-1 disks onto the target.

Examples

Example 1
Input
1
Output
1
A C
Example 2
Input
2
Output
3
A B
A C
B C

Constraints

  • 1 ≤ n ≤ 10
Solve this task to unlock the editorial.

AI tutor

Stuck? Get a nudge — the tutor explains the idea, it never hands you the solution.