Java Reference
In-Depth Information
Software Engineering Observation 18.1
Any problem that can be solved recursively can also be solved iteratively. A recursive
approach is normally preferred over an iterative approach when the recursive approach more
naturally mirrors the problem and results in a program that is easier to understand and
debug. A recursive approach can often be implemented with fewer lines of code. Another
reason to choose a recursive approach is that an iterative one might not be apparent.
Performance Tip 18.2
Avoid using recursion in situations requiring high performance. Recursive calls take time
and consume additional memory.
Common Programming Error 18.2
Accidentally having a nonrecursive method call itself either directly or indirectly through
another method can cause infinite recursion.
18.8 Towers of Hanoi
Earlier in this chapter we studied methods that can be easily implemented both recursively
and iteratively. Now, we present a problem whose recursive solution demonstrates the el-
egance of recursion, and whose iterative solution may not be as apparent.
The Towers of Hanoi is one of the classic problems every budding computer scientist
must grapple with. Legend has it that in a temple in the Far East, priests are attempting to
move a stack of golden disks from one diamond peg to another (Fig. 18.10). The initial
stack has 64 disks threaded onto one peg and arranged from bottom to top by decreasing
size. The priests are attempting to move the stack from one peg to another under the con-
straints that exactly one disk is moved at a time and at no time may a larger disk be placed
above a smaller disk. Three pegs are provided, one being used for temporarily holding
disks. Supposedly, the world will end when the priests complete their task, so there's little
incentive for us to facilitate their efforts.
Let's assume that the priests are attempting to move the disks from peg 1 to peg 3. We
wish to develop an algorithm that prints the precise sequence of peg-to-peg disk transfers.
peg 1
peg 2
peg 3
Fig. 18.10 | Towers of Hanoi for the case with four disks.
 
 
Search WWH ::




Custom Search