"Program 1" Hanoi
title : The problem is to move a specified number of plates of different sizes from one tower to another, moving to conform to the following rules:
1) n plates are marked as 1,2,3,...,n, while three towers are labeled A, B, and C.
2) The plate cannot be placed above the smaller plate at any time.
3) Initial state, so the plates are placed on tower a.
4) only one plate can be moved at a time, and the plate must be located at the top of the tower.
The goal of this problem is to use tower C to move all the plates from tower A to Tower B.
Code:
1 ImportJava.util.Scanner;2 3 Public classTowerofhanoi {4 5 Public Static voidMain (string[] args) {6 //TODO auto-generated Method Stub7Scanner input =NewScanner (system.in);8System.out.println ("Enter Number of disks:");9 intn =input.nextint ();Ten OneSystem.out.println ("The Moves is:"); AMovedisks (n, ' A ', ' B ', ' C '); - } - the Public Static voidMovedisks (intNCharFromtower,CharTotower, - Charauxtower) { - if(n = = 1) -SYSTEM.OUT.PRINTLN ("Move disk" + N + "from" + Fromtower + "to" ++totower); - Else { +Movedisks (n-1, Fromtower, Auxtower, totower); ASYSTEM.OUT.PRINTLN ("Move disk" + N + "from" + Fromtower + "to" at+totower); -Movedisks (n-1, Auxtower, Totower, fromtower); - } - } -}View Code
Classic Java Programming issues