Skip to content

Commit 00776fd

Browse files
authored
Merge pull request #721 from sumitvajarinkar/tower-of-hanoi-java
Tower of hanoi java
2 parents f712d46 + 71981c8 commit 00776fd

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

Recursion/towerOfHanoi.java

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
//Tower of Hanoi
2+
//O(2^n)
3+
4+
/*
5+
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:
6+
7+
1. Only one disc move at time
8+
2. Follow order smaller always on the top of bigger
9+
3. Only top disc must be move
10+
11+
Here we considered three poles
12+
s=source d=destination h=helper
13+
14+
i/p: 1
15+
o/p: Move disc 1 from s to d
16+
17+
i/p: 2
18+
o/p: Move disc 1 from s to h
19+
Move disc 2 from s to d
20+
Move disc 1 from h to d
21+
22+
i/p: 3
23+
o/p:Move disc 1 from s to d
24+
Move disc 2 from s to h
25+
Move disc 1 from d to h
26+
Move disc 3 from s to d
27+
Move disc 1 from h to s
28+
Move disc 2 from h to d
29+
Move disc 1 from s to d
30+
31+
32+
No. of move : 2^n-1
33+
*/
34+
35+
import java.util.Scanner;
36+
37+
class towerOfHanoi{
38+
static void toh(char s,char d,char h,int n){
39+
if(n==1){
40+
System.out.println("Move disc "+n+" from "+s+" to "+d+"\n");
41+
return;
42+
}
43+
toh(s,h,d,n-1);
44+
System.out.println("Move disc "+n+" from "+s+" to "+d+"\n");
45+
toh(h,d,s,n-1);
46+
}
47+
public static void main(String[] args) {
48+
System.out.println("Enter no. of discs\n");
49+
Scanner sc = new Scanner(System.in);
50+
int n =sc.nextInt();
51+
sc.close();
52+
toh('s','d','h',n);
53+
54+
}
55+
}
56+
57+
58+

0 commit comments

Comments
 (0)