函数递归搞一搞,汉诺塔的游戏。
写完之后看了一眼网上大部分的做法都是在函数里直接加一个指针来计数,我用了一个全局变量,道理差不多,也能用。
#include<iostream>
using namespace std;
int cc = 0;
void supermove(char, char, char, int);
int main()
{
char anotherround;
do
{
cc = 0;
char bas, temp, des;
int n;
cout << "请输入起始柱名称:" << endl;
cin >> bas;
cout << "请输入目标柱名称:" << endl;
cin >> des;
cout << "请输入过程柱名称:" << endl;
cin >> temp;
cout << "请输入需要挪动的圆盘数:" << endl;
cin >> n;
supermove(bas, temp, des, n);
cout << "\n完成! 一共需要" <<cc<<"步"<< endl;
cout << endl;
cout<<"还需要再来一局吗?(y/n)"<<endl;
cin >> anotherround;
} while (anotherround == 'y');
cin.get();
return 0;
}
void supermove(char bas, char temp, char des, int n)
{
if (n > 2)
{
supermove(bas, des, temp, n - 1);
supermove(bas, temp, des, 1);
supermove(temp, bas, des, n - 1);
}
else if (n == 2)
{
cout << " " << bas << " --> " << temp << endl;
cout << " " << bas << " --> " << des << endl;
cout << " " << temp << " --> " << des << endl;
cc += 3;
}
else
{
cout << " " << bas << " --> " << des << endl;
cc += 1;
}
}
现在随便试了一下10个盘子,就1023步了,太多的没试过,时间太长了。