【问题标题】:Solving the Hanoi Puzzle with Recursion用递归解决河内难题
【发布时间】:2017-08-02 21:40:29
【问题描述】:

所以这里我有一个程序,显示解决河内难题的模拟。我的程序在大多数情况下都可以正常工作,但不会在应该终止的时候终止。一旦所有的圆盘都在 C 挂钩(C C C)上,它应该终止,但我的继续到第四个圆盘,但没有给出。应该只有三个光盘。任何帮助将不胜感激!

#include <iostream>
using namespace std;

const int num = 3;
const char from_peg = 'A';
const char to_peg = 'B';
const char temp_peg = 'C';

char position[num];
void moveDiscs(int num,int disc,char source,char dest, char spare){
    if (disc == 0){
        position[disc]=dest;
        cout<<"Moved disc "<<disc+1<<" to peg "<<dest;
        cout<<" ( ";
        for(int i = 0;i<num;i++){
            cout<<position[i]<<" ";
        }
        cout<<")"<<endl;
    }else{
        moveDiscs(num,disc-1,source,spare,dest);
        position[disc]=dest;
        cout<<"Moved disc "<<disc+1<<" to peg "<<dest;
        cout<<" ( ";
                for(int i = 0;i<num;i++){
                    cout<<position[i]<<" ";
                }
                cout<<")"<<endl;
        moveDiscs(num,disc-1,spare,dest,source);
    }
}
int main() {

    cout<<"Starting Position for 3 discs are (";
    for(int i = 0;i<num;i++){
        position[i]='A';
        cout<<position[i]<<" ";
    }
    cout<<")"<<endl;


    moveDiscs(3,3,from_peg,to_peg,temp_peg);
    return 0;
}

输出:

Starting Position for 3 discs are (A A A )
Moved disc 1 to peg C ( C A A )
Moved disc 2 to peg B ( C B A )
Moved disc 1 to peg B ( B B A )
Moved disc 3 to peg C ( B B C )
Moved disc 1 to peg A ( A B C )
Moved disc 2 to peg C ( A C C )
Moved disc 1 to peg C ( C C C )
Moved disc 4 to peg B ( C C C )
Moved disc 1 to peg B ( B C C )
Moved disc 2 to peg A ( B A C )
Moved disc 1 to peg A ( A A C )
Moved disc 3 to peg B ( A A B )
Moved disc 1 to peg C ( C A B )
Moved disc 2 to peg B ( C B B )
Moved disc 1 to peg B ( B B B )

【问题讨论】:

  • position[disc]=dest; 在来自main 的第一次调用中使用else 块中的越界索引修改position
  • 看起来 if 块正在检查磁盘 0-3,而在 else 中它最终输出 disc+1。不会“给出”答案,但看看你如何比较光盘和输出应该会让你走上正确的轨道。
  • Aren't vectors fun? -- 即时诊断问题。

标签: c++ computer-science


【解决方案1】:

正如@Das 指出的那样,您的光盘从 0 开始,但是您将 discs = 3 的数量传递给 03 的光盘总数实际上是 4(同样的错误通常发生在数组长度上)。您实际上应该将 discs 设置为等于 2。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-25
    • 2016-01-27
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 2013-08-31
    • 2015-10-08
    • 2018-12-30
    相关资源
    最近更新 更多