汉诺塔初级问题(递归实现)

汉诺塔

 

Time Limit: 1000ms   Memory limit: 65536K  有疑问?点这里^_^

题目描述

汉诺塔(又称河内塔)问题是印度的一个古老的传说。
开天辟地的神勃拉玛在一个庙里留下了三根金刚石的棒A、B和C,A上面套着n个圆的金片,最大的一个在底下,其余一个比一个小,依次叠上去,庙里的众僧不倦地把它们一个个地从A棒搬到C棒上,规定可利用中间的一根B棒作为帮助,但每次只能搬一个,而且大的不能放在小的上面。
僧侣们搬得汗流满面,可惜当n很大时这辈子恐怕就很搬完了。
聪明的你还有计算机帮你完成,你能写一个程序帮助僧侣们完成这辈子的夙愿吗?

输入

输入金片的个数n。这里的n<=10。

输出

输出搬动金片的全过程。格式见样例。

示例输入

2

示例输出

Move disk 1 from A to B
Move disk 2 from A to C
Move disk 1 from B to C

提示

可以用递归算法实现。
 
  
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <iomanip>
#include <string>
#include <algorithm>

using namespace std;

void hanoi(int n, char a, char b, char c )
{
    if(n==1)
    {
        printf("Move disk %d from %c to %c
", n, a, c);
    }
    else
    {
        hanoi(n-1, a, c, b);
        printf("Move disk %d from %c to %c
", n, a, c );
        hanoi(n-1, b, a, c);
    }
}

int main()
{
    int n;
    while(scanf("%d", &n)!=EOF)
    {
        hanoi(n, 'A', 'B', 'C');
    }
    return 0;
}
原文地址:https://www.cnblogs.com/yspworld/p/4090825.html