The tower of Hanoi

Source: Internet
Author: User

The tower of Hanoi consists of three rods, and a number of disks of different sizes which can slide onto any rod. the puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.

The objective of the puzzle is to move the entire stack to another rod, obeying the following rules:

  • Only one disk may be moved at a time.
  • Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod.
  • No disk may be placed on top of a smaller disk.
Java code:
public class Hanoi {    private static int i = 1;    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub        int n;        System.out.print("Please enter the number of dish:");        Scanner scan = new Scanner(System.in);        n = scan.nextInt();        hanoi(n, 'A', 'B', 'C');    }    public static void hanoi(int n, char a, char b, char c){        if(n>0){            hanoi(n-1, a, c, b);            System.out.println("Step " + i + ". Move dish " + n + " from pile " + a + " to " + b);            i++;            hanoi(n-1, c, b, a);        }    }}
Input:
Please enter the number of dish:3
Output:
Step 1. Move dish 1 from pile A to BStep 2. Move dish 2 from pile A to CStep 3. Move dish 1 from pile B to CStep 4. Move dish 3 from pile A to BStep 5. Move dish 1 from pile C to AStep 6. Move dish 2 from pile C to BStep 7. Move dish 1 from pile A to B

 

 

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.