Double color Hanoi Tower problem

Source: Internet
Author: User

Two-color Hanoi tower problem: The disc was originally mixed color from small to large row, now requires according to its color separate to two pillars from small to large row. The three-colour Hanoi tower problem can be similar to that of three pillars.

Similar to the Hanoi tower problem, slightly changed, assuming that the column number is ABC, a total of n disk (n is even)

1. Move the top n-1 disc from A to B above

2. Move the bottom disc from a to C

3. Move the n-2 disc on the B column to a, thus creating a scenario like the second diagram


Therefore, we can solve this problem according to a recursive solution.



Double color Hanoi tower problem #include <iostream> using namespace std;
int removetimes = 0;
	void hanoiorignal (int nmovnum, char Czsource, Char Cztemp, char czdes) {if (Nmovnum = 0) {return; else if (Nmovnum = 1) {cout<< ' move the ' <<nmovnum<< ' disk from ' <<czsource << ' to ' &
		lt;<czdes<<endl;
	removetimes++;
		else {hanoiorignal (nmovnum-1, Czsource, Czdes, cztemp);
		cout<< ' Move the ' <<nmovnum<< ' disk from ' <<czsource << ' to ' <<czdes<<endl;
		removetimes++;
	Hanoiorignal (Nmovnum-2, Cztemp, Czdes, Czsource);
	} void Hanoitwocolor (int ndisk) {char Szsource = ' a ';
	char sztemp = ' B ';
	char szdes = ' C ';
	for (int i = Ndisk i > 0; i-= 2) {hanoiorignal (Ndisk, Szsource, sztemp, szdes);
	cout<< "Total number of moves:" <<removeTimes<<endl;

Removetimes = 0;
	} void Main () {int ndisknum = 0;
	cout<< "The number of discs on the input tower must be a multiple of 2, enter 0 end" <<endl;
	cin>>ndisknum; while (Ndisknum) {
		Hanoitwocolor (Ndisknum);
		cout<< "The number of discs on the input tower must be a multiple of 2, enter 0 end" <<endl;
	cin>>ndisknum;
System ("pause");
 }
Input a total of 6 disks, the output is as follows:




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.