Java Examples - Tower of Hanoi Algorithm
The Tower of Hanoi (also known as the Tower of Brahma) is a puzzle originating from an ancient Indian legend. When Brahma created the world, he made three diamond pillars, with 64 golden disks stacked on one pillar in order of size from bottom to top. Brahma ordered the Brahmins to rearrange the disks on another pillar in order of size, starting from the bottom. The rules are that a larger disk may not be placed on a smaller disk, and only one disk may be moved at a time between the three pillars.
Later, this legend evolved into the Tower of Hanoi game, played as follows:
- 1. There are three rods A, B and C. Rod A holds a number of disks
- 2. Move one disk at a time, and a smaller disk can only be stacked on a larger one
- 3. Move all disks from rod A to rod C
The following example demonstrates the implementation of the Tower of Hanoi algorithm:
MainClass.java File
public
class
MainClass
{
public
static
void
main
(
String
[
]
args
)
{
int
nDisks
=
3
;
doTowers
(
nDisks
,
'
A
'
,
'
B
'
,
'
C
'
)
;
}
public
static
void
doTowers
(
int
topN
,
char
from
,
char
inter
,
char
to
)
{
if
(
topN
==
1
)
{
System
.
out
.
println
(
"
Disk 1 from
"
from
"
to
"
to
)
;
}
else
{
doTowers
(
topN
1
,
from
,
to
,
inter
)
;
System
.
out
.
println
(
"
Disk
"
topN
"
from
"
from
"
to
"
to
)
;
doTowers
(
topN
1
,
inter
,
from
,
to
)
;
}
}
}
The output of the above code is:
Disk 1 from A to C
Disk 2 from A to B
Disk 1 from C to B
Disk 3 from A to C
Disk 1 from B to A
Disk 2 from B to C
Disk 1 from A to C
Java Examples