我正在尝试使用递归为学校项目制作带有7个磁盘的河内塔,我不确定是什么问题,但是输出完全错误。我认为它与moveDisk()函数有关,但是我找不到问题。步数正确。任何帮助将非常感激。这是我的代码,如果您有任何疑问,请发表评论:
//#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <cassert>
using namespace std;
struct Peg
{
vector<int> peg;
string name;
};
void loadDisk(int diskNum, vector<int> &startPeg)
{
assert(startPeg.size() == 0);
for (int i = diskNum; i > 0; i--)
{
startPeg.push_back(i);
}
}
void printPeg(int diskNum, vector<int> peg, string name)
{
cout << name << endl;
assert(peg.size() >= 0);
if (peg.size() > 0)
{
for (unsigned int i = 0; i < peg.size(); i++)
{
cout << peg[i];
}
}
cout << endl << endl;
}
void moveDisk(vector<int> &startPeg, vector<int> &goalPeg)
{
if (goalPeg.size() == 0)
{
int temp = startPeg.back();
startPeg.pop_back();
goalPeg.push_back(temp);
}
}
int hanoi(int diskNum, vector<int> &startPeg, vector<int> &goalPeg, vector<int> &tempPeg)
{
int count = 0;
if (diskNum == 0)
{
moveDisk(startPeg, goalPeg);
}
else
{
count = hanoi(diskNum - 1, startPeg, tempPeg, goalPeg);
moveDisk(startPeg, goalPeg);
count++;
count += hanoi(diskNum - 1, tempPeg, goalPeg, startPeg);
}
return count;
}
int main()
{
Peg startPeg, tempPeg, goalPeg;
startPeg.name = "Start";
tempPeg.name = "Temp";
goalPeg.name = "Goal";
int diskNum = 7;
loadDisk(diskNum, startPeg.peg);
cout << "Starting Conditions with three pegs: " << endl;
printPeg(diskNum, startPeg.peg, startPeg.name);
printPeg(diskNum, tempPeg.peg, tempPeg.name);
printPeg(diskNum, goalPeg.peg, goalPeg.name);
int moveCount = hanoi(diskNum, startPeg.peg, tempPeg.peg, goalPeg.peg);
cout << "End Conditions with three pegs: " << endl;
printPeg(diskNum, startPeg.peg, startPeg.name);
printPeg(diskNum, tempPeg.peg, tempPeg.name);
printPeg(diskNum, goalPeg.peg, goalPeg.name);
cout << moveCount << " total moves were taken." << endl;
system("pause");
return 0;
}
,当前输出为: 三钉的起跑条件: 开始 7654321
温度
目标
使用三个钉子结束条件: 开始 76543
温度 2
目标 1
总共采取了127个动作。
答案 0 :(得分:0)
-b