1

我有一个关于河内线性塔的问题。

我在 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;
 }
}

我究竟做错了什么?

4

2 回答 2

1

From wikipedia:

Simple solution: The following solution is a simple solution for the toy puzzle.

Alternate moves between the smallest piece and a non-smallest piece. When moving the smallest piece, always move it in the same direction (to the right if the starting number of pieces is even, to the left if the starting number of pieces is odd). If there is no tower in the chosen direction, move the piece to the opposite end, but then continue to move in the correct direction. For example, if you started with three pieces, you would move the smallest piece to the opposite end, then continue in the left direction after that. When the turn is to move the non-smallest piece, there is only one legal move. Doing this should complete the puzzle using the least amount of moves to do so.

于 2009-10-20T21:35:59.557 回答
0

您可以将代码转换为持续传递样式。然后一切都是尾递归的......

于 2009-11-27T20:50:39.413 回答