-
Notifications
You must be signed in to change notification settings - Fork 353
/
Copy pathTowerOfHanoi.cpp
46 lines (29 loc) · 1.11 KB
/
TowerOfHanoi.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
/* Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
1. Only one disk can be moved at a time.
2. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
3. No disk may be placed on top of a smaller disk.
*/
#include<iostream>
using namespace std;
void towerofHanoi(int n, char src, char helper ,char dest){// number of element , source, helper, destination
if(n==0){
return; //base case
}
towerofHanoi(n-1, src, dest, helper);// Move n-1 disks from source to helper
cout<<"Move from "<<src<<" to "<<helper<<endl;
towerofHanoi(n-1, dest, helper, src);// Move n-1 disks from destination to helper
}
int main(){
towerofHanoi(3, 'A', 'B', 'C');// A = Source , B = helper, C = destination.
return 0;
}
/* Input = 3
Output:
Move from A to B
Move from A to C
Move from B to C
Move from A to B
Move from C to A
Move from C to B
Move from A to B
*/