21-04-20:第一次自己写出了递归代码(3柱汉诺塔问题,pta lab6-9),纪念一下。
#include<iostream>
#include<string>
using namespace std;
int depth = 0;
void Towermove(string s1,string s3,int n,string s2){
depth++;
if(depth>1000) return;//避免堆栈溢出造成段错误
if(n==1){
cout<<s1<<"->"<<s3<<endl;
return;//attention:must have a "return" with base case.
}
Towermove(s1,s2,n-1,s3);
cout<<s1<<"->"<<s3<<endl;
Towermove(s2,s3,n-1,s1);
}
int main(){
int N;
string sa,sb,sc;
cin>>N>>sa>>sb>>sc;
Towermove(sa,sc,N,sb);
return 0;
}
/*
本来我想的函数是只有目的地和盘子数的,这样在把n的问题拆解为n-1的问题时会出现问题。
然后我看wiki里的思路提示,这不是和我想的一样吗?可是这样不能正确地把问题拆解啊!
后来我明白了,可以增加函数的参数。
*/
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。