Tower of Hanoi
Send Feedback
1) Only one disk can be moved at a time.
2) A disk can be moved only if it is on the top of a rod.
3) No disk can be placed on the top of a smaller disk.
Integer n
Steps in different lines (in one line print source and destination rod name separated by space)
0 <= n <= 20
2
a b
a c
b c
3
a c
a b
c b
a c
b a
b c
a c
SOLUTION:-
#include <iostream>
using namespace std;
void towerOfHanoi(int n, char source, char auxiliary, char destination) {
// Write your code here
if(n==0)
return;
if(n==1)
cout<<source<<' '<<destination<<endl;
else if(n==2)
{
cout<<source<<' '<<auxiliary<<endl;
cout<<source<<' '<<destination<<endl;
cout<<auxiliary<<' '<<destination<<endl;
}
else{
towerOfHanoi(n-1,source,destination,auxiliary);
cout<<source<<' '<<destination<<endl;
towerOfHanoi(n-1,auxiliary,source,destination);
}
}
int main() {
int n;
cin >> n;
towerOfHanoi(n, 'a', 'b', 'c');
}
This is dummy text. It is not meant to be read. Accordingly, it is difficult to figure out when to end it. But then, this is dummy text. It is not meant to be read. Period.
If you have any doubts then please let me know... ConversionConversion EmoticonEmoticon