输出汉诺塔的移动步骤

《输出汉诺塔的移动步骤》

对于汉诺塔问题的求解,可以通过以下三个步骤实现:

  1. 将塔A上的n-1个碟子借助塔C先移到塔B上。

  2. 把塔A上剩下的一个碟子移到塔C上。

  3. 将n-1个碟子从塔B借助塔A移到塔C上。

#include <iostream>
using namespace std;

void hannuo(int a, int b, int c, int n) {
    if (n == 1) {
        cout << "move disk " << n << " from peg " << a << " to peg " << c << endl;
    } else {
        hannuo(a, c, b, n - 1);
        cout << "move disk " << n << " from peg " << a << " to peg " << c << endl;
        hannuo(b, a, c, n - 1);
    }
}

int main(void) {
    int times;
    cin >> times;
    while (times--) {
        int n;
        cin >> n;
        hannuo(1, 2, 3, n);
    }
}
    原文作者: 汉诺塔问题
    原文地址: https://blog.csdn.net/desirepath/article/details/50487958
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞