Hanoi Principle Analysis:
When there is only one plate, you need to move from a tray on tower A to Tower C.
When there are two plates on tower A, move the No. 1th plate on Tower A (numbered from top to bottom) to Tower B, then move the No. 2nd plate on Tower C and move the small plate on Tower B to Tower C.
When there are 3 plates on tower A, move the plates numbered 1 to 2 on tower A to Tower B (with the help of Tower C), move the largest plate on tower A to tower C, and finally move the 3rd plates on Tower B to Tower C with the help of Tower A.
When there are n plates on tower A, move the plate numbered 1 to n-1 (n-1) on Tower A to Tower B (with tower C), then move the largest n plate on tower A to Tower C, and then move the n-1 tray on Tower B to Tower C with a tower.
To sum up, except that there is only one plate without the use of other towers, the rest is the same.
[CPP]View Plaincopy
- <span style= "FONT-SIZE:14PX;" > #include <iostream>
- using namespace &NBSP;STD;&NBSP;&NBSP;
- int hannuota ( int n,string a,string b,string c)
- {&NBSP;&NBSP;
- if (n==1)
- &NBSP;&NBSP;&NBSP;&NBSP;{&NBSP;&NBSP;
- //with only one plate, move the plate on the first tower directly to the third tower &NBSP;&NBSP;
- printf (" tower%s------> Tower%s\n " ,a.c_str (), C.c_str ());
- &NBSP;&NBSP;&NBSP;&NBSP;}&NBSP;&NBSP;
- else {
- //1. First the n-1 plate of the first tower is moved through the third tower to the second tower. &NBSP;&NBSP;
- hannuota (n-1,a, c, b);
- //2. Move the remaining plate to the third tower. &NBSP;&NBSP;
- printf (" tower%s------> Tower%s\n " ,a.c_str (), C.c_str ());
- //3. Finally, the plate on the second tower is moved through the first tower to the third tower. &NBSP;&NBSP;
- Hannuota (n-1, B, A, c);
- }
- return 1;
- }
- intMain (intargc,Const Char* argv[]) {
- printf (" Please enter the number of plates: \ n "
- int n;
- scanf ("%d " ,&n);
- printf (" the plate moves as follows: \ n "
- hannuota (N," A " " B " " C "
- return 0;
- }</span>
Hanoi using recursive algorithm