Thursday, February 21, 2013

Iterative Solution for Tower of Hanoi in Java

Going through some practice problems, and came across the Tower of Hanoi. The implementation of the iterative solution follows the following steps (borrowed from the wiki article):

"Simpler statement of iterative solution
Alternating between the smallest and the next-smallest disks, follow the steps for the appropriate case:
For an even number of disks:
-make the legal move between pegs A and B
-make the legal move between pegs A and C
-make the legal move between pegs B and C
-repeat until complete
For an odd number of disks:
-make the legal move between pegs A and C
-make the legal move between pegs A and B
-make the legal move between pegs C and B
-repeat until complete In each case, a total of 2ⁿ-1 moves are made."

Code: IterativeHanoi.java

No comments:

Post a Comment