我对河内的线性塔楼有疑问。

我在C++中实现了它,但是我尝试使用尾部递归或迭代方法执行相同的操作。我的算法遇到问题。

此代码段显示了从中间塔架到末端塔架的传输块。

#include <stdlib.h>
#include <stdio.h>
using namespace std;

//int a[5]={2,3,1,2,1};
int from,spare,to;

int main()
{
//int n;

//void hanoi(int,int,int,int);
void linear_hanoi(int,int,int,int);
void mid_to_end(int,int,int,int);
void end_to_mid(int,int,int,int);
//mid_to_end(3,2,3,1);
end_to_mid(4,3,2,1);
getchar();
return 0;
}

void linear_hanoi(int n, int from, int to, int spare)
{
     if(n>0)
      {
            linear_hanoi(n-1,from,to,spare);
            cout<<"move ring "<<n<<" from tower "<<from<<" to tower "<<spare<<endl;
            linear_hanoi(n-1,to,from,spare);
            cout<<"move ring "<<n<<" from tower "<<spare<<" to tower "<<to<<endl;
            linear_hanoi(n-1,from,to,spare);
      }
}
void mid_to_end(int n, int from, int to, int spare)
{
  if(n>0)
  {
     mid_to_end(n-1,from,spare,to);
     cout<<"move ring "<<n<<" from tower "<<from<<" to tower "<<to<<endl;
    // mid_to_end(n-1,spare,from,to);
   //  mid_to_end(n-1,from,to,spare);
   //cout<<"move ring "<<n<<" from tower "<<spare<<" to tower "<<from<<endl;
  // mid_to_end(n-1,from,to,spare);
    //cout<<"move ring "<<n<<" from tower "<<spare<<" to tower "<<from<<endl;
 }
}

我究竟做错了什么?

最佳答案

从维基百科:

简单的解决方案:
以下解决方案是玩具拼图的简单解决方案。

在最小的片段和非最小的片段之间交替移动。移动最小的一块时,请始终沿相同的方向移动(如果起始块数为偶数,则向右移动,如果起始块数为奇数,则向左移动)。如果在选定的方向上没有塔,则将部件移至另一端,然后继续沿正确的方向移动。例如,如果从三块开始,则将最小的块移到另一端,然后在那之后继续向左移动。当轮到移动最小的零件时,只有一个合法的 Action 。这样做应该以最少的 Action 完成拼图。

10-01 14:41
查看更多