Tower of Hanoi (Hanoi)

Source: Internet
Author: User

Algorithm Analysis:

If there are three plates on tower A, need to move to Tower C, according to certain rules, the need for the use of Tower B, the case of movement is as follows:



When there are 3 plates, a total of 2^3-1 steps are required, and when there are n plates, a 2^n-1 step is required.


Algorithm implementation:

<span style= "Font-family:microsoft yahei;font-size:18px;" ><? PHP
//Hanoi Tower implements
//n plates, x, Y, Z, three pillars.
 function Hanoi ($n, $x, $y, $z) {
        if ($n = = 1) {
               echo ' move 1 from '. $x. "To" $z. " </br> ";
        } else{
               Hanoi ($n-1, $x, $z, $y);//The n-1 plate is moved from x through Y to the z
            echo "move". $n. "From" $x. "to" $z. " </br> ";
            Hanoi ($n-1, $y, $z, $x);//N-1 a plate by x from Y to Z
        }
 }
 Hanoi (3, ' x ', ' y ', ' z ');</span>


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.