Java Learning (3): Recursion problem (example: Hanoi tower problem).

Source: Internet
Author: User

The recursive problem is one of the common problems in writing programs. This essay explains the problem of the Nottingham tower with obvious recursion.

1 ImportJava.util.Scanner;2 3 /**4 * Recursion: Hanoi5  *6  * @authorXCX7 * @time July 3, 2017 morning 8:16:078  */9  Public classHanoi {Ten     Private Static inti = 0; One  A      Public Static voidMain (string[] args) { -         intn = 0; -Scanner reader =NewScanner (system.in); theSystem.out.println ("Please enter the number of plates:"); -n =reader.nextint (); -The solution of SYSTEM.OUT.PRINTLN (n + "layer Hanoi is:"); -Move (n, ' A ', ' B ', ' C '); +System.out.println ("Total:" +i); -     } +  A     Private Static voidMoveintNoCharACharBCharC) { ati++; -         if(No = = 1) {//If there is only one plate, move the plate directly from a to C -SYSTEM.OUT.PRINTLN ("Move plate 1 from" + A + "to" +C); -}Else{//if the number of plates is greater than 1 -                 //first move the n-1 plate from A to B . -Move (no-1, A, C, B); in             //and move the nth plate to C . -SYSTEM.OUT.PRINTLN ("Move plate" + No + "from" + A + "to" +C); to             //and then move the n-1 plate from B to C . +Move (no-1, B, A, C); -         } the  *     } $ Panax Notoginseng}

Hanoi Tower Problem Analysis: N indicates the number of plates

if n = 1: Move the plate directly from A to C

If n > 1: Move (n-1) a plate from A to B, and then move (n-1) the plate from B to C

Java Learning (3): Recursion problem (example: Hanoi tower problem).

Related Article

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.