C++實現漢諾塔問題
阿新 • • 發佈:2019-01-28
#include <iostream> using namespace std; void hanoi(int N,char source,char relay,char destination){ //遞迴函式的定義 if(N==1) //遞迴終結條件:N==1 cout<<source<<"->"<<destination<<endl; //直接把這個盤子從source移動到destination else{ hanoi(N-1,source,destination,relay); //先把上面N-1個盤子移到relay cout<<source<<"->"<<destination<<endl; hanoi(N-1,relay,source,destination); } } int main(){ int n; cout<<"請輸入漢諾塔的層數: "; cin>>n; hanoi(n,'A','B','C'); //呼叫遞迴函式將n個盤子從A轉移到C (藉助B) return 0; }