（出自C++大学教程英文版第226页）

The Towers of Hanoi is one of the most famous classic problems every budding computer scientist must  grapple with . Legend has it that in a temple in the Far East , priests are attempting to move a stack of  golden disks from one diamond peg to another . The initial stack has 64 disks threaded onto  one peg and arranged from bottom to top by decreasing size . The priests are attempting to move the stack  from one peg to another under the constraints that exactly one disk is moved at a time and at no time may a larger disk be placed above a smaller disk . Three pegs are provided , one being used for temporarily  holding disks . Supposedly , the world will end when the priests complete their task , so there is little  incentive for us to facilitate their efforts .

Let’s assume that the priests are attempting to move the disks from peg1 to peg3. We wish to develop an algorithm that prints the precise sequence of peg-topeg disk transfers.

Display the precise instructions for moving the disks from starting peg to the destination peg. To move a stack of three disks from peg1 to peg3, the program displays the following moves:

1->3

1->2

3->2

1->3

2->1

2->3

1->3

C++代码实现

#include<cstdio>
using namespace std;
int js=0;
void calculate(int num, int from, int to,int tmp )
{
if (num == 1)
{
printf("%d->%d\n", from, to);
js++;
}
else
{
calculate(num - 1,from, tmp,to);
calculate(1, from, to, tmp);
calculate(num - 1, tmp, to, from);
}
}

int main()
{
int n;
scanf_s("%d", &n);
calculate(n, 1, 3, 2);
printf("\nSTEPS=%d", js);
}

C++

C++

C++

C++