Difficulty level: Silver
3145 questions about the Nottingham Tower
Title Description Description
Hanoi Tower Problem (also known as Hanoi problem), is a well-known problem. On the a,b,c three pillars, there are n different sizes of discs (assuming the radii are 1-n), and at first they are stacked on my A (), and your goal is to move all the plates from tower A to tower C within the minimum number of legally moving steps.
The rules for each step in the game are as follows:
1. Each step is allowed to move only one plate (from the top of one pillar to the top of another)
2. In the process of moving, you must ensure that the large plate cannot be on the top of the small plate (small can be placed on the large top, the maximum plate can not have any other size plate)
For the case of n=3, a valid moving sequence:
1 from A to C
2 from A to B
1 from C to B
3 from A to C
1 from B to A
2 from B to C
1 from A to C
Give a number n to find a moving sequence with a minimum number of steps
Enter a description input Description
An integer n
outputs description output Description
The first line is an integer k, which represents the minimum number of moving steps.
The next K-line, one sentence per line, n from x to Y, indicates that the N-number plate is moved from the X-column to the Y-column. X, Y belongs to {a,b,c}
sample input to sample
3
Sample output Sample outputs
7
1 from A to C
2 from A to B
1 from C to B
3 from A to C
1 from B to A
2 from B to C
1 from A to C
data size & Hint
n<=10
Set the HN to move the n plates from the A to the C-bar. Obviously, when n=1, simply move the plate on the a column directly to the C-pillar, so h1=1. When n=2, the small plate above the A column is moved to the B-pillar, then the large plate is moved from the A-column to the C-pillar, and finally, the small plate on the B-pillar is moved to the C-pillar, a total of 3 disks, so h2=3 When there are N (n>=2) plates on the A column, always move the upper n-1 tray to the B-pillar with the C-pillar, then move the bottom plate of the A-pillar to the C-pillar, and then move the n-1 plate on the B-pillar to the C-pillar by the A-pillar, and move the hn-1+1+hn-1 in total.
∴ recursion: Relational hn=2*hn-1+1 boundary Condition: h1=1
That is, Hn=2 's n-square-1
#include <iostream>#include<cstdio>#include<cmath>using namespacestd;intn,s;CharA,b,c;//Set 3 pillars for A,b,c, respectively .voidDfsintNCharACharBCharC//move N on a to C with the help of B{ if(n==1) {printf ("%d from%c to%c\n", N,a,c); return; } DFS (n-1, a,c,b);//move the n-1 on a with C to B .printf"%d from%c to%c\n", n,a,c);//move the last one on a to C .DFS (N-1, b,a,c);//move the n-1 on B to C with a.}intMain () {CIN>>N; cout<<pow (2, N)-1<<Endl; DFS (N,'A','B','C');}
codevs3145 Hanoi Tower Problem