在递归河内塔中,我怎样才能保持三个数组(支柱)的顺序?

In recursive Hanoi Tower how can I keep the three arrays (pillars) in order?

我写了一个河内塔程序,但是因为递归的原因,输出切换了A、B、C柱。有没有办法保留柱子以制作动画? 我的代码:

#include <iostream>
#include <vector>
#include <stdlib.h> 
#include <windows.h> 
using namespace std;

void printTowers(vector<int>& arr1, vector<int>& arr2, vector<int>& arr3)
{
    printOut(arr1); //prints vector using iterator
    printOut(arr2);
    printOut(arr3);
}
//------------
//  hanoi(number of disks, source pillar, spare pillar, target pillar)
void hanoi(int d, vector<int>& a, vector<int>& b, vector<int>& c)
{
    if(d == 1)
    {
        c.push_back(a.back());
        a.pop_back();
        printTowers(a,b,c); 
    }
    else{
    hanoi(d-1,a,c,b);
    hanoi(1,a,b,c);
    hanoi(d-1,b,a,c);
    }
}
//------------
int main()
{
    int n = 3; 
    vector <int> A, B, C;
    A.reserve(n); B.reserve(n); C.reserve(n);

    for(int i=0; i<n; i++)
    {
        A.push_back(n-i);
    }    
    hanoi(n,A,B,C);   
    return 0;
}

示例输出:

 321 | 32 | 3  |    |    | 2  |    |    |
     |    | 1  | 3  | 21 | 3  | 1  |    |
     | 1  | 2  | 21 | 3  | 1  | 32 | 321|

期望的输出:

 321 | 32 | 3  | 3  |    | 1  | 1  |    |
     |    | 2  | 21 | 21 | 2  |    |    |
     | 1  | 1  |    | 3  | 3  | 32 | 321|

您可以在向量中使用一个额外的单元格来告诉您它是什么支柱。例如

vector <int> A, B, C;
A.reserve(n+1); B.reserve(n+1); C.reserve(n+1);
A.push_back(-1);
B.push_back(-2);
C.push_back(-3);

现在

//add a new function to simplify code
void printTowerId(vector<int>& arr1, vector<int>& arr2, vector<int>& arr3, int id){  
    if(arr1[0] == id) printOut(arr1);
    if(arr2[0] == id) printOut(arr2);
    if(arr3[0] == id) printOut(arr3);
}

你原来的函数看起来像

void printTowers(vector<int>& arr1, vector<int>& arr2, vector<int>& arr3)
{
    printTowerId(arr1, arr2, arr3, -1);
    printTowerId(arr1, arr2, arr3, -2);
    printTowerId(arr1, arr2, arr3, -3);
}

注意在你的递归中不要占用你添加的单元格