-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtower-of-hanoi.cpp
83 lines (78 loc) · 1.69 KB
/
tower-of-hanoi.cpp
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
#include <iostream>
#include <stack>
using namespace std;
void moveDisk(stack<int> &start, stack<int> &dest)
{
int disk = start.top();
start.pop();
dest.push(disk);
}
void printTower(stack<int> tower)
{
while (!tower.empty())
{
int disk = tower.top();
tower.pop();
for (int i = 0; i < disk; i++)
{
cout << "*";
}
cout << endl;
}
}
void playTowerOfHanoi(int numDisks)
{
stack<int> tower1, tower2, tower3;
for (int i = numDisks; i >= 1; i--)
{
tower1.push(i);
}
while (tower3.size() != numDisks)
{
printTower(tower1);
printTower(tower2);
printTower(tower3);
cout << "Move disk from: ";
int start, dest;
cin >> start;
cout << "Move disk to: ";
cin >> dest;
if (start == 1 && dest == 2)
{
moveDisk(tower1, tower2);
}
else if (start == 1 && dest == 3)
{
moveDisk(tower1, tower3);
}
else if (start == 2 && dest == 1)
{
moveDisk(tower2, tower1);
}
else if (start == 2 && dest == 3)
{
moveDisk(tower2, tower3);
}
else if (start == 3 && dest == 1)
{
moveDisk(tower3, tower1);
}
else if (start == 3 && dest == 2)
{
moveDisk(tower3, tower2);
}
else
{
cout << "Invalid move!" << endl;
}
}
cout << "Congratulations, you solved the puzzle!" << endl;
}
int main()
{
int numDisks;
cout << "Enter the number of disks: ";
cin >> numDisks;
playTowerOfHanoi(numDisks);
return 0;
}