我在河内塔问题上挣扎了3个月。这是我能找到的最简单的代码:
void moveDisk(int n, char from, char to, char buffer)
{
if(n == 1)
{
cout << "Move disk 1 from " << from << " to " << to << endl;
return;
}
moveDisk(n-1, from, buffer, to);
cout << "Move disk " << n << " from " << from << " to " << to << endl;
moveDisk(n-1, buffer, to, from);
}
int main()
{
moveDisk(3, 'A', 'C', 'B');
}
效果很好:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
我最大的问题是:为什么有效?
我已经做过一些研究,他们都说:“将前n-1个磁盘移至'buffer',然后将n个磁盘移至'to'栈,最后将前n-1个磁盘移至“到”堆栈。我理解它的想法,但我的问题是:为什么编写这种方式的代码行得通?另外:为什么我们需要打印:
cout << "Move disk 1 from " << from << " to " << to << endl;
在基本情况下才能正常工作?如果按照上述想法,为什么我们在遇到基本情况时就不返回?
我试图手动跟踪递归,并且变量“ from”,“ to”和“ buffer”不断变化-但以某种方式起作用!
请向我解释为什么?
谢谢!