[C++] 河內塔問題
河內塔問題很適合用來練習遞迴技巧(Recursion)跟分治法的演算法技巧(Divide and Conquer)這個程式碼輸入要放幾個盤子,執行過程也可以顯示要搬移第幾個盤子從哪個柱子到哪個住子#include <iostream>
#include <cstdlib>
using namespace std;
long int times;
void Hanoi(int disks, int src, int dst, int No)
{
if ( disks == 1 )
{
cout << ++times << ": Move Disk." << No << " (" << src << ") → (" << dst << ")" << endl;
return;
}
// 棒子編號 1 2 3 編號總和 6
int aux = 6 - src - dst;
Hanoi((disks-1), src, aux, (No-1));
Hanoi(1, src, dst, No);
Hanoi((disks-1), aux, dst, (No-1));
}
int main(void)
{
int count;
cout << "輸入盤子數:";
cin >> count;
times = 0;
Hanoi(count, 1, 2, count);
cout << "------------" << endl;
cout << "移動" << count << "個盤子,需要移動" << times << "次";
system("pause");
}
頁:
[1]