Recursion--Hanoi tower problem (Python implementation)

Source: Internet
Author: User

Rules
    1. Move one plate at a time
    2. At any time the big plates are down, the small plates are on top.
Method

Assuming a total of n plates

    • When N=1:
      1. Move a plate on the A directly to C (A->C)
    • When n=2:
      1. Put the small plate from A to B (a->b) here to start using parameters, RSC Source address =a,dst Destination address =b
      2. Put the big plate from A to C (a->c)rsc=a, Dst=c
      3. Put the small plate from B to C (b->c)rsc=b, Dst=c
    • When n=3:
      1. Put two plates on a, move through C to B, call recursive implementation (A-C->B)rsc=a, trans Transit =c, Dst=b
      2. Move the largest remaining plate on a to C (a->c)rsc=a, Dst=c
      3. Put two plates on B, with the aid of A, move to C up, call recursion (b-a->c)rsc=b, Trans=a, Dst=c
    • When N=n:

      1. N-1 a plate on a, with the help of C, move to B, call recursion (a-c->b)rsc=a, trans=c, Dst=b

      2. Move the largest plate on a to C (a->c)rsc=a, Dst=c

      3. N-1 a plate on B, with the aid of a, move to C, call recursion (b-a->c)rsc=b, Trans=a, Dst=c

Each time the other disc is moved to the auxiliary pillar, then the bottom of the move to C, and then the original pillar as a secondary pillar, repeat

Code implementation
def move(n, a, b, c):'''汉诺塔的递归实现n:代表几个盘子a:代表第一个塔,rscb:代表第二个塔,transc:代表第三个塔, dst'''    if n == 1:        print(a, '=>', c)    else:        move(n-1, a, c, b)        print(a, '=>', c)        move(n-1, b, a, c)

Recursion--Hanoi tower problem (Python implementation)

Related Article

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.