Home > Java > javaTutorial > java example - Tower of Hanoi algorithm

java example - Tower of Hanoi algorithm

黄舟
Release: 2017-02-07 10:56:15
Original
1398 people have browsed it

The Tower of Hanoi (also known as the Tower of Hanoi) is an educational toy derived from an ancient legend in India. When Brahma created the world, he made three diamond pillars. On one pillar, 64 gold discs were stacked in order of size from bottom to top. Brahma ordered the Brahmin to rearrange the disks on another pillar in order of size from the bottom. It is also stipulated that the disk cannot be enlarged on the small disk, and only one disk can be moved between the three pillars at a time.

Later, this legend evolved into the Tower of Hanoi game, and the gameplay is as follows:

1. There are three poles A, B, and C. There are several plates on pole A

2. Move one plate at a time, the smaller one can only be stacked on top of the larger one

3. Move all the dishes from pole A to pole C

The following example demonstrates the implementation of the Tower of Hanoi algorithm:

/*
 author by w3cschool.cc
 MainClass.java
 */
public class MainClass {
   public static void main(String[] args) {
      int nDisks = 3;
      doTowers(nDisks, 'A', 'B', 'C');
   }
   public static void doTowers(int topN, char from,
   char inter, char to) {
      if (topN == 1){
         System.out.println("Disk 1 from "
         + from + " to " + to);
      }else {
         doTowers(topN - 1, from, to, inter);
         System.out.println("Disk "
         + topN + " from " + from + " to " + to);
         doTowers(topN - 1, inter, from, to);
      }
   }
}
Copy after login

The output result of the above code is:

Disk 1 from A to C
Disk 2 from A to B
Disk 1 from C to B
Disk 3 from A to C
Disk 1 from B to A
Disk 2 from B to C
Disk 1 from A to C
Copy after login


The above is the java example - The content of the Tower of Hanoi algorithm, for more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template