One usage of recurison: The Tower of Hanoi

Source: Internet
Author: User

Statements: This blog was written by me, but most of content is quoted from book [Data Structure with Java hubbard] [Description]

 We have seen important examples of functions that are more naturally defined and more easily understood by using recursion. foe some problem, recursion is the only reasonable method of solution. the towers of Hanoi puzzle is a classical example of a problem whose solution demands recursion. the game consists of a board with three vertical pegs labeled A, B, and C, and a sequence of N disks with holes in their centers. the radii of the disks are in an arithmetic sion ssion (eg, 6 cm, 7 cm, 8 cm); and are mounted on Peg. the rule is that no disk may be abve a smaller disk on the same peg. the objective of the game is to move all the disks from peg a to peg C, one disk at a time, without violating the rule.


[Implement] The program prints the solution to the towers of Hanoi Problem of moving three disk from peg a to peg C via peg B.
Package COM. alberta Shao. DS. recursion; // data structures with Java, Second Edition // by John R. hubbard // Copyright 2007 by McGraw-hillpublic class testhanoitowers {public static void main (string [] ARGs) {hanoitowers (3, 'A', 'B ', 'C');} public static void hanoitowers (int n, char X, char y, char Z) {If (n = 1) {// basis system. out. printf ("move Top disk from Peg % C to peg % C. % N ", x, z);} else {hanoitowers (n-1, X, Z, Y); // recursion hanoitowers (1, x, y, z ); // recursion hanoitowers (n-1, Y, x, z); // recursion }}}
[Result]

Move top disk from peg a to peg C. move top disk from peg a to peg B. move top disk from Peg C to peg B. move top disk from peg a to peg C. move top disk from Peg B to peg. move top disk from Peg B to peg C. move top disk from peg a to peg C.





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.