我对河内塔有意见。我知道如何建造普通的河内塔,很简单:
void solveTowers(char src, char dst, char mid, int n)
{
if (n == 0)
{
return;
}
solveTowers(src, mid, dst, n - 1);
cout << "Move " << ++counter << ": disk " << n << " from " << src << " to " << dst << endl;
solveTowers(mid, dst, src, n - 1);
}
但现在我想建两座塔:
在第一张照片中,我们看到了普通的河内塔,在第二张照片中,我想做一些东西现在我想要一根棍子(?)只有偶数圈,只有奇数圈。
你能帮我吗?
最佳答案
正如我在注释中所建议的,您可以从外部函数多次调用solveTowers()以下代码对我很有用:
void solveTowers(int src, int dst, int mid, int n, vector<vector<int>>& pegs) {
if (n == 0) {
return;
}
solveTowers(src, mid, dst, n - 1, pegs);
cout << "Moving disk " << n << " from " << src << " to " << dst << endl;
int t = pegs[src].back();
pegs[src].pop_back();
pegs[dst].push_back(t);
cout<<"pegs:\n";for(int r=0;r<pegs.size();++r){for(int c=0;c<pegs[r].size();++c)cout<<pegs[r][c]<<"\t";cout<<"\n\n";}cout<<endl;
solveTowers(mid, dst, src, n - 1, pegs);
}
void solve_odd_even(int n) {
vector<vector<int>> pegs(3);
for (int i = 0; i < n; ++i) {
pegs[0].push_back(n - i);
}
int dst = 1;
int mid = 2;
if (n % 2)
swap(dst, mid);
solveTowers(0, dst, mid, n, pegs);
for (int h = n - 1; h > 0; --h) {
int src = 1;
int dst = 2;
if (h % 2 == 0)
swap(src, dst);
solveTowers(src, dst, 0, h, pegs);
}
}
int main(int argc, char* argv[]) {
solve_odd_even(atoi(argv[1]));
return 0;
}
关于algorithm - build 奇偶汉诺塔,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30082472/