Java data structure and algorithm example: Hanoi tower problem Hanoi_java

Source: Internet
Author: User
/** * Hanoi The University of the time to learn, but did not understand, the only thing to know is to use the recursive method to solve. * Problem Description: * There are three poles a,b,c. 
 There are N (n>1) perforated discs on a pole, and the size of the disk is smaller from bottom to top. 
 * Require the following rules to move all discs to C: * 1. Only one disc can be moved at a time; * 2. The market can not be stacked on the small plate. 
 * Hint: The disc can be temporarily placed in B bar, can also be removed from a rod to move back to a rod, * but must respect the above two rules. * Q: How to move? 
 How many times do I have to move at least? * Solution: * Assuming that there are only 2 plates, the pillars are a, B, c column respectively. 
 Then it takes only three steps to move them from column A to column C, which is A->b, A->c, B->c. 
 * If the number of plates N is more than 2, we can think of these plates as the bottom of the plate and the top of the n-1 plate two parts, * These two parts can also be moved by the three steps above. 
 * That means we can move all n plates from column A to column C by recursively calling the steps above. 
* * Package Al; 
    public class Hanoi {public static void main (string[] args) {Hanoi Hanoi = new Hanoi (); 
  Hanoi.move (3, ' A ', ' B ', ' C '); 
  }/** * @author * @param n Plate number * @param from the starting post * @param temp Intermediate pillar * @param to target post * * public void Move (int n, char from, Char temp, char to) {if (n = = 1) {System.out.println ("Move 1 plate from 
    ' + from + ' to ' + to '; 
      else {Move (n-1, from, to, temp); 
      Move (1, from, temp, to); Move (n-1, temp, from, to);
    } 
  } 
}  

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.