(Towers of Hanoi) Modify Listing, TowersOfHanoi.cpp, so that the program finds the number of moves needed to move ndisks from tower A to tower B. (Hint:Use a global variable and increment it every time the function is called.)
Listing TowersOfHanoi.cpp
1 #include
2 using namespace std;
3
4 // The function for finding the solution to move n disks
5 // from fromTower to toTower with auxTower
6 void moveDisks(int n, char fromTower, char toTower, char auxTower)
7 {
8 if (n == 1) // Stopping condition
9 cout << "Move disk ” << n << ” from ” <<<
10 fromTower << " to " << toTower << endl;
11 else
12 {
13 moveDisks(n - 1, fromTower, auxTower, toTower);
14 cout << "Move disk " << n << " from " <<<
15 fromTower <<< " to " << toTower << endl;
16 moveDisks(n - 1, auxTower, toTower,fromTower);
17 }
18 }
19
20int main()
21 {
22 // Read number of disks, n
23 cout << "Enter number of disks: ";
24 int n;
25 cin >> n;
26
27 // Find the solution recursively
28 cout << "The moves are: " << endl;
39 moveDisks(n, 'A', 'B', 'C');
30
31 return 0 ;
32 }
We need at least 10 more requests to produce the solution.
0 / 10 have requested this problem solution
The more requests, the faster the answer.