使用递归解决河内难题

时间:2017-08-02 02:40:57

标签: c++ computer-science

我目前正在创建一个程序,显示解决河内谜题的每一步。我需要显示从开始位置开始的每个移动的每个盘的位置为(A,A,A)。 A =第一个桩,B =第二个桩,C =第三个桩。我有程序输出移动但不是位置。如何在计划中实施职位?到目前为止,这是我的代码,输出和图表显示了每次移动后的位置。光盘数量为常数3。

#include <iostream>
using namespace std;

void moveDiscs(int num,int fromPeg,int toPeg, int tempPeg){;
char position;
    if(num > 0){
        moveDiscs(num-1,fromPeg,tempPeg,toPeg);
        cout << "Move a disc from peg "<<fromPeg<<" to peg "<<toPeg<<endl;
        moveDiscs(num-1,tempPeg,toPeg,fromPeg);
    }
}
int main() {
    const int from_peg = 1;
    const int to_peg = 3;
    const int temp_peg = 2;

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

Output

Diagram of Positions

1 个答案:

答案 0 :(得分:0)

以下是跟踪每个动作和每个钉子位置的解决方案 我正在使用stl :: map peg A有3,2,1 peg B,空,peg C,空(必须完成移动。

目前的解决方案基于约束可以根据约束变化进行更新

#include <iostream>
#include <map>
#include <deque>
using namespace std;

map<int,deque<int>> bucket;
deque<int> A{3,2,1};
deque<int> B;
deque<int> C;



void moveDiscs(int num,int fromPeg,int toPeg, int tempPeg){;
    if(num > 0){
        moveDiscs(num-1,fromPeg,tempPeg,toPeg);
        cout << "Move a disc from peg "<<fromPeg<<" to peg "<<toPeg<<endl;
        auto val = bucket[fromPeg].front();
        bucket[fromPeg].pop_front();
        bucket[toPeg].push_front(val);
        for (auto it:bucket)
        {
            cout << it.first << "::";
            for (auto di = it.second.begin(); di != it.second.end(); di++)
            {
                cout << "=>" << *di;
            }
            cout << endl;
        }

        moveDiscs(num-1,tempPeg,toPeg,fromPeg);
    }
}
int main() {

    bucket[1] = A;
    bucket [2] =B;
    bucket[3] = C;
    const int from_peg = 1;
    const int to_peg = 3;
    const int temp_peg = 2;

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

输出

Move a disc from peg 1 to peg 3
1::=>2=>1
2::
3::=>3
Move a disc from peg 1 to peg 2
1::=>1
2::=>2
3::=>3
Move a disc from peg 3 to peg 2
1::=>1
2::=>3=>2
3::
Move a disc from peg 1 to peg 3
1::
2::=>3=>2
3::=>1
Move a disc from peg 2 to peg 1
1::=>3
2::=>2
3::=>1
Move a disc from peg 2 to peg 3
1::=>3
2::
3::=>2=>1
Move a disc from peg 1 to peg 3
1::
2::
3::=>3=>2=>1
Program ended with exit code: 0

所以你可以看到Peg A(1 :: 3 =&gt; 2 =&gt; 1)被移动到peg C(3 :: 3 =&gt; 2 =&gt; 1)