1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
|
// Hanoi Puzzle.cpp : main project file.
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
using namespace std;
static vector<int> source, tempo, destin;
void StartTower(vector<int> &src, vector<int> &dest, vector<int> &temp, int numDisks, int &counter)
{
cout << "Starting disks : ";
counter++;
for (vector<int >::const_iterator iter = src.begin(); iter != src.end(); ++iter)
cout << *iter << " ";
cout << " | ";
//cout << "dest: ";
for (vector<int >::const_iterator iter = dest.begin(); iter != dest.end(); ++iter)
cout << *iter << " ";
cout << " | ";
//cout << "temp: ";
for (vector<int >::const_iterator iter = temp.begin(); iter != temp.end(); ++iter)
cout << *iter << " ";
cout << endl;
}
void hanoiTower(vector<int> &src, vector<int> &dest, vector<int> &temp, int numDisks, int &counter, int shuffle[3] )
{
string label[3] = { "Src", "Dest", "Temp" };
if (numDisks == 0)
return;
shuffle[0] = 0;
shuffle[1] = 2;
shuffle[2] = 1;
hanoiTower(src, temp, dest, numDisks - 1, counter,shuffle);
dest.push_back(src.back());
src.pop_back();
cout << "Move #" << counter << ": ";
counter++;
for (int show = 0; show < 3; show++)
{
switch (shuffle[show])
{
case 0:
{
cout << label[shuffle[show]] << " : ";
for (vector<int >::const_iterator iter = src.begin(); iter != src.end(); ++iter)
cout << *iter << " ";
cout << " | ";
}
break;
case 1:
{
cout << label[shuffle[show]] << " : ";
for (vector<int >::const_iterator iter = dest.begin(); iter != dest.end(); ++iter)
cout << *iter << " ";
cout << " | ";
}
break;
case 2:
{
cout << label[shuffle[show]] << " : ";
for (vector<int >::const_iterator iter = temp.begin(); iter != temp.end(); ++iter)
cout << *iter << " ";
cout << " | ";
}
break;
}
}
cout << endl;
shuffle[0] = 2;
shuffle[1] = 1;
shuffle[2] = 0;
hanoiTower(temp, dest, src, numDisks - 1, counter, shuffle);
}
int main() {
int numDisks, counter = 0, shuffle[3] = { 0, 1, 2 };
cout << "Enter the tower height: ";
cin >> numDisks;
for (int i = 0; i < numDisks; i++)
{
source.push_back(numDisks - i);
}
//Show initial disk placement
StartTower(source, destin, tempo, numDisks, counter);
// Solve tower
hanoiTower(source, destin, tempo, numDisks, counter, shuffle);
cout << endl << "Tower of Hanoi, solved.. Game finished." << endl;
cin >> counter;
}
|