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
|
#include <iostream>
using namespace std;
void Hanoi2(string, string, string, string, int, bool);
void Hanoi1(string start, string dest, string a2, string a3, int n)
{
if(n==1)
{
cout << "Move disk " << n << " from " << start << " to " << dest << endl;
}
else
{
Hanoi2(start, dest, a2, a3, n-1, false);
cout << "Move disk " << n << " from " << start << " to " << dest << endl;
Hanoi1(a3, start, dest, a2, n-1);
Hanoi1(start, dest, a2, a3, n-1);
}
}
void Hanoi2(string start, string a2, string a3, string dest, int n, bool isFlagged)
{
if(n==1)
{
// if(isFlagged == true)
// start = "start";
// cout << "Move disk " << n << " from " << start << " to " << dest << endl;
if(isFlagged == 1)
cout << "Move disk " << n << " from start to " << dest << endl;
else
cout << "Move disk " << n << " from " << start << " to " << dest << endl;
}
else
{
Hanoi2(start, a2, a3, dest, n-1, isFlagged);
// if(isFlagged == true)
// start = "start";
// cout << "Move disk " << n << " from " << start << " to " << a3 << endl;
if(isFlagged == 1)
cout << "Move disk " << n << " from start to " << a3 << endl;
else
cout << "Move disk " << n << " from " << start << " to " << a3 << endl;
Hanoi1(dest, start, a2, a3, n-1);
cout << "Move disk " << n << " from " << a3 << " to " << dest << endl;
Hanoi2(start, a2, a3, dest, n-1, false);
}
}
void Hanoi3(string start, string a1, string a2, string a3, string dest, int n, bool isFlagged)
{
if(n==1)
{
cout << "Move disk " << n << " from " << start << " to " << dest << endl;
}
else
{
Hanoi2(a1, a1, a2, a3, n-1, isFlagged);
cout << "Move disk " << n << " from start to a1" << endl;
cout << "Move disk " << n << " from a1 to a2" << endl;
Hanoi1(a3,a1,a1,a2, n-1);
cout << "Move disk " << n << " from a3 to dest" << endl;
Hanoi3(a1,a2,a2,a3,dest,n-1,false);
}
}
int main()
{
Hanoi3("start", "a1", "a2", "a3", "dest", 3, true);
return 0;
}
| |