forked from dimpeshpanwar/javabasicprograms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TowerOfHanoi
22 lines (22 loc) · 835 Bytes
/
TowerOfHanoi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class TowerOfHanoi{
static int count = 0;
static void recursive_toh(int N, char from, char to, char using){
if (N == 1) {
// base condition. If only one disk is there we can directly move it to the target
System.out.println ("Removing Disk 1 from rod"+ from +" and placing on rod" +to);
count = count+1;
return;
}
// see the code explanation part for a clear understanding of these 3 lines
recursive_toh( N-1, from, using, to);
System.out.println ("Removing Disk "+N+" from rod"+ from +" and placing on rod" +to);
count = count+1;
recursive_toh( N-1, using, to, from);
}
public static void main(String[] args) {
int N = 4; //Number of disks
recursive_toh(N,'1','3','2'); // Meaning of this line is
// Move N disks from rod 1 to rod 3 using rod 2
System.out.println("Minimum No of disk movements for "+N+" disks is "+count);
}
}