汉诺塔(递归)

<pre name="code" class="cpp">#include <iostream>
using namespace std;

/*
method:每次处理两个盘子,A->B,A->C.B->C
*/
void hanoi(int n, char A, char B, char C) 
{ 
	if(n == 1) 
	{ 
		cout<<"move sheet "<<n<<" from "<<A<<" to "<<C<<endl;
	} 
	else 
	{ 
		hanoi(n-1, A, C, B); 
		cout<<"move sheet "<<n<<" from "<<A<<" to "<<C<<endl;
		hanoi(n-1, B, A, C); 
	} 
} 


int main() {
	int n; 
	cout<<"please input the number of sheet:"<<endl; 
	cin>>n;
	hanoi(n, 'A', 'B', 'C'); 
	return 0; 
}
点赞