12
12
13
13
The objective of the puzzle is to move the entire stack to the last rod, obeying the following rules:
14
14
15
- Only one disk may be moved at a time.
15
+ Only one disk may be moved at a time.
16
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.
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
18
19
- No disk may be placed on top of a disk that is smaller than it.
19
+ No disk may be placed on top of a disk that is smaller than it.
20
20
21
21
With 3 disks, the puzzle can be solved in 7 moves.
22
22
23
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
24
25
-
26
- */
25
+ */
27
26
28
27
#include < iostream>
29
28
using std::cout;
@@ -39,13 +38,13 @@ size_t solve_tower(int n, char first, char second, char third)
39
38
}
40
39
41
40
// move n-1 disks from first to other using second as a placeholder
42
- size_t num_moves = solve_tower (n - 1 , first, second, third );
41
+ size_t num_moves = solve_tower (n - 1 , first, third, second );
43
42
44
43
// move the nth disk from first to second
45
- cout << " Move disk " << n << " from " << first << " to " << second << " \n " ;
44
+ cout << " Move disk " << n << " from " << first << " to " << third << " \n " ;
46
45
47
46
// move the n-1 disks from third to second using first as an placeholder
48
- num_moves += solve_tower (n - 1 , third , first, second );
47
+ num_moves += solve_tower (n - 1 , second , first, third );
49
48
50
49
// return the total moves plus 1
51
50
return num_moves + 1 ;
@@ -60,7 +59,7 @@ int main()
60
59
char c = ' C' ;
61
60
62
61
// number of disks to move in puzzle
63
- size_t num_disk = 4 ;
62
+ size_t num_disk = 3 ;
64
63
65
64
// find the total number of moves needed to solve
66
65
size_t num_moves = solve_tower (num_disk, a, b, c);
0 commit comments