跳转至

汉诺塔[[递归]]

代码:

#include <iostream>

#include <algorithm>

#include <cstring>

using namespace std;



void move(int n, char begin, char via, char to){

    if(n == 1){

        cout << "move " << n << " from " << begin << " to " << to << endl;

        return;

    }

    move(n - 1, begin, to, via);

    cout << "move " << n << " from " << begin << " to " << to << endl;

    move(n - 1, via, begin, to);

}



int main(){

    int n;

    cout << "输入盘子的个数" << endl;

    cin >> n;

    move(n, 'A', 'B', 'C');



    return 0;

}

函数说明

void move(int n, char begin, char via, char to){

    if(n == 1){

        cout << "move " << n << " from " << begin << " to " << to << endl;

        return;

    }

    move(n - 1, begin, to, via);

    cout << "move " << n << " from " << begin << " to " << to << endl;

    move(n - 1, via, begin, to);

}
  • 参数说明:
    • 将第n个利用begin经过via移动到to
  • 函数解释
    • 如果是1个盘子,直接从begin移动到to
    • 否则
      • 先将begin上的n-1个盘子从begin借助to移动到via上暂存
      • 再将剩下的一个盘子从begin直接移动到to
      • 再将via上的n-1个盘子从via借助begin移动到to