Hanoi recursive algorithm

Source: Internet
Author: User

#-*-Coding:utf-8-*-# author:keekuun "" "There are three Poles a,b,c. A rod has N (n>1) perforated discs, the size of the disk from bottom to top in turn smaller. The following rules are required to move all discs to the C-bar: Only one disc can be moved at a time; the market cannot be stacked on a small plate. "" "Time = 0def mov (n, a, B, c):    global"    when there is only one disc if    n = = 1:        print (A, '--', B    # when there are n disks when    else:        # n = (n-1) +1, first move the n-1 discs to B        mov (n-1, A, C, b)        # to move the largest disk 1 directly to C        mov (1, a, B, c)        # again Move the n-1 disk from B to C        mov (n-1, B, A, c)    return Timeprint (mov (1, ' A ', ' B ', ' C ')) print (' * ' *10) print (MOV (2, ' A ', ' B ', ' C ') Print (' * ' *10) print (MOV (3, ' A ', ' B ', ' C ')) print (' * ' *10) print (MOV (4, ' A ', ' B ', ' C '))

Output

A-and B
1
**********
A-and C
A-and B
B--A
4
**********
A-and B
A-and C
C--A
A-and B
B--C
B--A
A-and B
11
**********
A-and C
A-and B
B--A
A-and C
C--B
C--A
A-and C
A-and B
B--A
B--C
C--B
B--A
A-and C
A-and B
B--A
26

Hanoi recursive algorithm

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.