【C++_Practice_函数递归】汉诺塔

/*
汉诺塔
 有三根针A、B、C。A针上有N个盘子,大的在下,小的在上,
 要求把这N个盘子从A针移到C针,在移动过程中可以借助B针,
 每次只允许移动一个盘,且在移动过程中在三根针上都保持大盘在下,小盘在上。
 */

#include <iostream>
using namespace std;

void move(char src, char dest)
{
    cout << src << " --> " << dest << endl;
}

void hanoi(int n, char src, char medium, char dest)
{
    if(n == 1)
        move(src, dest);
    else
    {
        hanoi(n - 1, src, dest, medium);
        move(src, dest);
        hanoi(n - 1, medium, src, dest);
    }
}

int main()
{
    int m;
    cout << "Enter the number of diskes: ";
    cin >> m;
    cout << "The step to moving " << m << "diskes: " << endl;
    hanoi(m, 'A', 'B', 'C');
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_30638419/article/details/85445810