Skip to content

Commit f3cb5fe

Browse files
authored
Merge pull request #586 from harshita9621/master
Tower of Hanoi
2 parents cf44bbc + 0443409 commit f3cb5fe

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

DSA 450 GFG/TowerOfHanoi.cpp

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
2+
/* 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:
3+
4+
1. Only one disk can be moved at a time.
5+
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.
6+
3. No disk may be placed on top of a smaller disk.
7+
*/
8+
9+
#include<iostream>
10+
using namespace std;
11+
12+
void towerofHanoi(int n, char src, char helper ,char dest){// number of element , source, helper, destination
13+
14+
15+
if(n==0){
16+
return; //base case
17+
}
18+
19+
towerofHanoi(n-1, src, dest, helper);// Move n-1 disks from source to helper
20+
cout<<"Move from "<<src<<" to "<<helper<<endl;
21+
towerofHanoi(n-1, dest, helper, src);// Move n-1 disks from destination to helper
22+
23+
24+
25+
}
26+
27+
int main(){
28+
29+
towerofHanoi(3, 'A', 'B', 'C');// A = Source , B = helper, C = destination.
30+
31+
return 0;
32+
33+
34+
}
35+
/* Input = 3
36+
37+
Output:
38+
39+
Move from A to B
40+
Move from A to C
41+
Move from B to C
42+
Move from A to B
43+
Move from C to A
44+
Move from C to B
45+
Move from A to B
46+
*/

0 commit comments

Comments
 (0)