Object Oriented Data Structures Using Java Small

advertisement
492
|
Chapter 7: Programming with Recursion
To move the largest circle (circle 4) to peg 3, we must move the three smaller circles to
peg 2 (this cannot be done with 1 move). Then circle 4 can be moved into its final place:
1
2
3
4
1
1
2
3
2
1
3
2
4
3
1
2
1
3
2
AM
FL
Y
Let’s assume we can do this. Now, to move the next largest circle (circle 3) into place,
we must move the two circles on top of it onto an auxiliary peg (peg 1 in this case):
1
2
4
3
1
3
4
2
3
TE
To get circle 2 into place, we must move circle 1 to another peg, freeing circle 2 to
be moved to its place on peg 3:
1
2
1
2
3
3
4
2
3
4
1
1
2
3
The last circle (circle 1) can now be moved into its final place, and we are finished:
1
1
2
1
2
3
4
2
3
4
3
1
The general algorithm for moving n circles from peg 1 to peg 3 is:
Get n Circles Moved from Peg 1 to Peg 3
Get n ! 1 circles moved from peg 1 to peg 2
Move the nth circle from peg 1 to peg 3
Get n ! 1 circles moved from peg 2 to peg 3
Team-Fly®
2
3
Download