河內塔
為了要記錄河內塔問題的圓盤移動位置,所以將每個圓盤與柱子進行編號,編號方式如下:
.圓盤的編號由上到下(小到大)分別為 1, 2, 3, …
.柱子編號為 A, B, C,初始狀態的圓盤在柱子 A,最終目標狀態則是將所有圓盤移動至柱子 C
每次移動圓盤時,將移動的過程記錄下來並且輸出
Input
輸入一個數字為圓盤的總數
Output
將每一次移動圓盤的過程輸出一行,例如將圓盤 1 從柱子 A 移動到柱子 C,輸出則印出:
Move disk 1 from A to C
範例輸入:
3
範例輸出:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
/*----- ----- ----- -----*/ //2-Hanoi //Made by 105502555 Teemo Hsu(Synasaivaltos) //Date: 2018/03/21 /*----- ----- ----- -----*/ #include <iostream> using namespace std; void hanoi(int n,char x,char y,char z) { if(n==1) cout << "Move disk " << n << " from " << x << " to " << z << endl; else { hanoi(n-1,x,z,y); cout << "Move disk " << n << " from " << x << " to " << z << endl; hanoi(n-1,y,x,z); } } int main(void) { int n; cin >> n; hanoi(n,'A','B','C'); return 0; } |