Challenge: Tower of Hanoi
Completed
Move n discs from peg A to peg C using peg B; one disc at a time, never a bigger disc on a smaller one. Print each move as Move disc <d> from <X> to <Y>, then Total moves: <count>.
Input
One whole number n (1 ≤ n ≤ 6).
Output
The moves, then the total.
Example
Input
1
Output
Move disc 1 from A to C Total moves: 1
Editor
C++
Hints
Move n - 1 discs to the spare peg, move disc n, then move the n - 1 discs on top of it.
Solution explanation
It takes 2ⁿ − 1 moves: a classic O(2ⁿ) algorithm.
Show solution
#include <iostream>
using namespace std;
int moves = 0;
void hanoi(int n, char from, char via, char to) {
if (n == 0) return;
hanoi(n - 1, from, to, via);
cout << "Move disc " << n << " from " << from << " to " << to << endl;
moves++;
hanoi(n - 1, via, from, to);
}
int main() {
int n;
cin >> n;
hanoi(n, 'A', 'B', 'C');
cout << "Total moves: " << moves << endl;
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module