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).