注册 登录
编程论坛 C++教室

[求助]汉诺塔问题

a8451727 发布于 2007-07-02 22:47, 921 次点击

如下面汉诺塔的递归,要怎样才能得出A、B、C的移动次数?
递归中可以用 int i; i++; cout<<i; 计算次数吗?或可以用什么办法?

#include<iostream>
using namespace std;

void move(int n,char source,char destination,char spare);

int main()
{
const char PEG1='A',
PEG2='B',
PEG3='C';

cout<<"This program solves the Hanoi Towers puzzle.\n\n";
cout<<"Enter the nuimber of disks: ";
int numDisks;
cin>>numDisks;
cout<<endl;

move(numDisks,PEG1,PEG2,PEG3);
return 0;
}

void move(int n,char source,char destination,char spare)
{
if(n<=1)
cout<<"Move the top disk form "<<source<<" to "
<<destination<<endl;
else
{
move(n-1,source,spare,destination);
move(1,source,destination,spare);
move(n-1,spare,destination,source);
}
}

[此贴子已经被作者于2007-7-2 22:49:47编辑过]

11 回复
#2
aipb20072007-07-02 23:01
void move(int count,int start,int finish,int temp){
if(count > 0){
move(count-1,start,temp,finish);
cout << "move disk " << count << " form"
<< start << " to " << finish << ".\n";
move(count-1,temp,finish,start);
}
}

int main(){
move(3,1,3,2);
return 0;
}

try it out!

[此贴子已经被作者于2007-7-2 23:28:40编辑过]

#3
a84517272007-07-02 23:17
回复:(aipb2007)void move(int count,int start,in...

不行哦,运行结果这样的

#4
aipb20072007-07-02 23:22
结果难道不是这样?
你想要什么结果?
#5
a84517272007-07-02 23:28
[IMG]http://photo.store.qq.com/http_imgload.cgi?/rurl2=9c2d97f2c8e52c759898c024cdc05454a35f12a258cffc679fbf55fbde59672a1c028d4882b8a497e007928d7835bf89a5970f866307f559e5dbf703e89270d2e4483d28aeb294c9854541b5cdea3c81182bc858[/IMG]
我想把开头那全是1那也递归下去 123...N
也就是想得到他一共移动了几次。
#6
a84517272007-07-02 23:30
移动几次后,全部移完成。
#7
aipb20072007-07-02 23:32
我不太明白你的意思,我那个是模拟整个过程。
你是想要计算一共移动的次数吗?比如,3个盘,7次。
如果是,可以用记数+1。

不过,更简单的是 2^n-1 次,n是盘数。


还有,你程序中每次移动top,那个top是那个塔不清楚。
#8
a84517272007-07-02 23:41
嗯,就是想要一共移动的次数。就比如 A to c算一次A to b算一次,C to B又算一次。
是3个盘,移动7次这个数。
2^n-1可以得到移动次数了,谢谢了
#9
a84517272007-07-02 23:48
如果我想把每次移动记录下来,可以做到吗?
如:
1 A TO C
2 A TO B
3 C TO B
.....
N C TO B

第几步移动哪个。
也就是,我想让一个三岁小孩根据一步步来也能完成移动。

[此贴子已经被作者于2007-7-2 23:49:40编辑过]

#10
a84517272007-07-02 23:53

试过好多次都不懂该怎样做。

#11
aipb20072007-07-03 08:51
void move(int count,int start,int finish,int temp){
static int i = 1;
if(count > 0){
move(count-1,start,temp,finish);
cout << "step " << i++ << " : ";
cout << "move disk " << count << " form"
<< start << " to " << finish << ".\n";
move(count-1,temp,finish,start);
}
}

int main(){
move(3,1,3,2);
return 0;
}

[此贴子已经被作者于2007-7-3 8:52:25编辑过]

#12
a84517272007-07-03 12:21

谢谢了,可以了
原来要 static 做声明,我一直不懂

1