Recursive algorithm of Hanoi

Source: Internet
Author: User

How is Hanoi implemented by recursive algorithms?

This question bothered me for a while, and today I think it seems clear, so I'm going to record my thoughts here.

First, put the code on Python:

1 #-*-coding:utf-8-*-2 3 defMove (n,a,b,c):4     ifn = = 1:5        Print(A +" -"+c)6     ifn > 1:7Move (n-1, A,c,b)8        Print(A +" -"+c)9Move (n-1, B,a,c)Ten  OneMove (4,'A','B','C')

In order to complete this task, this parent task needs to be decomposed into three subtasks:

1. Move the n-1 on top of A to B

2. Move the bottom nth disk of a "to C"

3. Move the n-1 disk from B to C on the first step, and the task is completed.

The first task is to move the n-1 disk to B, through the code:

Move (N-1,A,C,B)

This is to tell the computer, one piece at a time, a n-1 on a disk to B, can be seen as a step to complete.

Next, move the nth disk in A to C:

Print (A +"--"+c)

At last:

Move (N-1,B,A,C)

Move all n-1 disks on B to C to complete the task.

Recursive algorithm of Hanoi

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.