2017-03-05 4 views
0

私はハノイ・タワー・プログラムを書いたが、再帰のため出力がA、B、Cピラーを切り替える。アニメーションを作るために柱を維持する方法はありますか? マイコード:再帰的なハノイ塔では、どのように3つの配列(柱)​​を順番に保つことができますか?

#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| 
+1

を追加したセルを占有しないように注意してくださいように見えます名前はそれぞれの柱の一部です。 –

答えて

0

あなたはそれが何であるかの柱を教えてくれ、あなたのベクトル内の余分なセルを使用することができます。例えば今

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); 
} 

は、あなたの再帰にあなたが

関連する問題