漢諾塔問題的C++實現

有三根杆子A,B,C。A杆上有N個(N>1)穿孔圓環,盤的尺寸由下到上依次變小。要求按下列規則將全部圓盤移至C杆:每次只能移動一個圓盤;大盤不能疊在小盤上面。如何移?最少要移動多少次?html

原理可參考: http://www.javashuo.com/article/p-ttrxxslj-go.html 中的講解ios


#include<iostream>
using namespace std;
void Hanoi(int,char,char,char);

int main()
{
    int n;
    cin >> n;
    Hanoi(n, 'a', 'b', 'c');
    system("pause");
    return 0;
}

void Hanoi(int n, char a, char b, char c)  //move a's plates to c column
{
    if (n == 1)
    {
        cout << "move plate " << n << " from " << a << " to " << c << endl; //move the last plate to the target column
    }
    else
    {
        Hanoi(n - 1, a, c, b); //move (n-1)*plate from a(previous column) to b(transition column)
        cout << "move plate " << n << " from " << a << " to " << c << endl;//move 'n' plate from a to target column
        Hanoi(n - 1, b, a, c); //move (n-1)*plate from b(transition column) to c(target column)
    }
}
相關文章
相關標籤/搜索