0
点赞
收藏
分享

微信扫一扫

汉诺塔(递归)

东言肆语 2022-03-12 阅读 84
c++

 考虑两步:

递归关系:要将A上的 n 个全移到C上,先把n - 1个移到B上,将最大个移到C上,再将B上的n - 1个移到C上;同理要将A上的n - 1个全移到B上,先把n - 2个移到C上,将最大个移到B上,再将C上的n - 2个移到B上;

以此构成递归关系,要将当前柱上的 x 个全移到目标柱上,先把x - 1个移到中间柱上,将最大个移到目标柱上,再将中间柱上的x - 1个移到目标柱上

递归出口:当n = 1时,直接将其移到目标柱上

#include <iostream>
using namespace std;
void hanoi (int n, char start, char temp, char target);
int main()
{
    int n;
    cin >> n;
    hanoi(n, 'A', 'B', 'C');
    return 0;
}

void hanoi(int n, char start, char temp, char target) {
    // 只有一个时,直接从开始移到目标柱
    if (n == 1) {
        cout << start << "->" << target << endl;
        return;
    }
    // 将上面的n-1移到中间柱
    hanoi(n - 1, start, target, temp);
    // 最大盘移到目标柱
    cout << start << "->" << target << endl;
    // 将中间柱的n-1移到目标柱
    hanoi(n - 1, temp, start, target);
}

 用x来记录当前最大盘的编号

#include <iostream>
using namespace std;
void hanoi (int n, char start, char temp, char target, int x);
int main()
{
    int n;
    char start, temp, target;
    cin >> n >> start >> temp >> target;
    hanoi(n, start, temp, target, n);
    return 0;
}

void hanoi(int n, char start, char temp, char target, int x) {
    // 只有一个时,直接从开始移到目标柱
    if (n == 1) {
        cout << x << ':' << start << "->" << target << endl;
        return;
    }
    // 将上面的n-1移到中间柱
    hanoi(n - 1, start, target, temp, x - 1);
    // 最大盘移到目标柱
    cout << x << ':' << start << "->" << target << endl;
    // 将中间柱的n-1移到目标柱
    hanoi(n - 1, temp, start, target, x - 1);
}
举报

相关推荐

0 条评论