1
+ /*
2
+ Recursive Towers of Hanoi Solution
3
+ Thomas Martin - 2023
4
+ https://github.com/thomas-martin-uf
5
+
6
+ Problem Description: (from wikipedia)
7
+ The Tower of Hanoi is a mathematical game or puzzle consisting of three rods and a number of disks of various diameters,
8
+ which can slide onto any rod.
9
+
10
+ The puzzle begins with the disks stacked on one rod in order of decreasing size, the smallest at the top,
11
+ thus approximating a conical shape.
12
+
13
+ The objective of the puzzle is to move the entire stack to the last rod, obeying the following rules:
14
+
15
+ Only one disk may be moved at a time.
16
+
17
+ Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or on an empty rod.
18
+
19
+ No disk may be placed on top of a disk that is smaller than it.
20
+
21
+ With 3 disks, the puzzle can be solved in 7 moves.
22
+
23
+ The minimal number of moves required to solve a Tower of Hanoi puzzle is 2^n − 1, where n is the number of disks.
24
+
25
+ */
26
+
27
+ #include < iostream>
28
+ using std::cout;
29
+
30
+ size_t solve_tower (int n, char first, char second, char third)
31
+ {
32
+
33
+ // recursive base case
34
+ if (n == 1 )
35
+ {
36
+ cout << " Move disk 1 from " << first << " to " << third << " \n " ;
37
+ return 1 ;
38
+ }
39
+
40
+ // move n-1 disks from first to other using second as a placeholder
41
+ size_t num_moves = solve_tower (n - 1 , first, third, second);
42
+
43
+ // move the nth disk from first to second
44
+ cout << " Move disk " << n << " from " << first << " to " << third << " \n " ;
45
+
46
+ // move the n-1 disks from third to second using first as an placeholder
47
+ num_moves += solve_tower (n - 1 , second, first, third);
48
+
49
+ // return the total moves plus 1
50
+ return num_moves + 1 ;
51
+ }
52
+
53
+ int main ()
54
+ {
55
+
56
+ // names of rods
57
+ char a = ' A' ;
58
+ char b = ' B' ;
59
+ char c = ' C' ;
60
+
61
+ // number of disks to move in puzzle
62
+ size_t num_disk = 3 ;
63
+
64
+ // find the total number of moves needed to solve
65
+ size_t num_moves = solve_tower (num_disk, a, b, c);
66
+
67
+ // output result
68
+ cout << " Total moves needed to solve: " << num_moves;
69
+ return 0 ;
70
+ }
0 commit comments