Hanoi Tower problem (Tower of Hanoi)

Source: Internet
Author: User

Hanoi : Hanoi (also known as Hanoi) is a puzzle toy from an ancient Indian legend. When big Brahma created the world, he made three diamond pillars, and stacked 64 gold discs on a pillar from bottom to top in order of size. The great Brahma commanded the Brahman to rearrange the discs from below to the other pillars in order of size. It is also stipulated that the disc cannot be enlarged on the small disc, and only one disc can be moved between the three pillars at a time.

Programming Ideas : The tower is divided into the top of the plate and the bottom of the market, and then the upper plate through the C-block move to block B, the last one to move the C-block, and then the B-disk in the N-1 a block to move to C block.

number of moves : 2^n-1.

C code :

#include <stdio.h>


int tower (int n,char A,char B,char C) {
if (n==1)
printf ("Move sheet%d from-%c to%c\n", n,a,c);
else{
Tower (N-1,A,C,B);
printf ("Move sheet%d from-%c to%c\n", n-1,a,c);
Tower (N-1,B,A,C);
}
return 0;
}
void Main () {
int n;
printf ("Please enter the number of disks:");
scanf ("%d", &n);
Tower (n, ' A ', ' B ', ' C ');

}

take the number of disks as an example of 3 to explain :

n=3;

Tower (2,A,C,B);

Tower (1,A,B,C);------>a->c

A->b

Tower (1,c,a,b)------>c->b

A->c

Tower (2,B,A,C);

Tower (1,b,c,a);------>b->a

B->c

Tower (1,a,b,c);------->a->c

End!

Program :

Hanoi Tower problem (Tower 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.