问题描述
在自学 C++ 的过程中,我遇到了河内塔问题,这是所有程序员显然都必须解决的经典递归练习。多亏了这里的一些答案,我已经慢慢但肯定地能够理解解决方案的部分工作原理,但我一直被最初的细节难住了。在迈出第一步之前,我似乎无法理解目标/目的地挂钩是如何更新的。例如,对于我研究过的一种解决方案:
#include <iostream>
using namespace std;
void tower(int,int,int);
int main() {
int num;
cout << "Enter the number of disks: "; cin >> num;
tower(num,1,3,2);
}
void tower(int numDisks,int initPeg,int tarPeg,int holdPeg) {
if (numDisks > 0) {
cout << "Target peg is: " << tarPeg << endl;
tower(numDisks - 1,initPeg,holdPeg,tarPeg);
cout << initPeg << "->" << tarPeg << endl;
tower(numDisks - 1,tarPeg,initPeg);
}
}
产生以下输出:
Enter the number of disks: 3
Target peg is: 3
Target peg is: 2
Target peg is: 3
1->3
1->2
Target peg is: 2
3->2
1->3
Target peg is: 3
Target peg is: 1
2->1
2->3
Target peg is: 3
1->3
我在目标挂钩输出语句中放置的位置以跟踪它在执行过程中的更新方式。首先,目标挂钩为 3,根据 tower(3,2);
输入后的调用 num = 3
。然后,在 tower(3,...)
中,再次调用该函数,这次是由 tower(numDisks - 1,tarPeg);
调用,现在似乎将目标挂钉指定为挂钉 2。到目前为止一切都很好。现在,在 tower(2,...)
中,该函数似乎被同一个 tower(numDisks - 1,tarPeg);
第三次调用,但输出清楚地再次显示 Target peg is: 3
,而不是 2。这是正确的移动,但是我不清楚目标挂钩如何更新为 tower(1,tarPeg)
中的挂钩 3,因为对于最后一次调用,它指定目标挂钩为挂钩 2。
有人可以对此有所了解吗?我尝试绘制两个磁盘的轨迹,一切看起来都不错。但是对于三个磁盘,我显然缺少一些东西。我希望我提出问题的方式是有道理的。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)