c_cpp 河内的塔

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 河内的塔相关的知识,希望对你有一定的参考价值。

#include <iostream>
#include <stack>

using namespace std;
typedef stack<int> ST;

//print a stack 
void print(std::string xx, ST & s1)
{
	ST tmp = s1; // copy it
	ST tmp2;

	// put it on another stack
	while (!tmp.empty())
	{
		tmp2.push(tmp.top());   tmp.pop();
	}

	cout << xx.c_str() << " ";

	// pop to print it.
	while (!tmp2.empty())
	{
		cout << tmp2.top() << " ";
		tmp2.pop();
	}
	cout << endl;
}

// from stack s1 to stack s2
bool moveOnce(ST & s1, ST & s2)
{
	if (s1.empty()) return false;

  // no need to check just move it.
	if (s2.empty())
	{
		s2.push(s1.top());
		s1.pop();
		return true;
	}
	// check legality
	else if ((s2.top() - s1.top()) >= 1)
	{
		s2.push(s1.top());
		s1.pop();
		return true;
	}

	return false;
}

// move in either direction that is legal between s1 & s2
bool moveEitherDirection(ST & s1, ST & s2)
{
	if (s2.empty()) return moveOnce(s1, s2);
	else if (s1.empty()) return moveOnce(s2, s1);
	else if (s1.top() < s2.top()) return moveOnce(s1, s2); 
	else return  moveOnce(s2, s1);
}

// print all stacks
void printall(std::string xx, ST & s1, ST & s2, ST & s3)
{
	print(xx + "1", s1);
	print(xx + "2", s2);
	print(xx + "3", s3);
	cout << endl;

}


void solution1(ST & s1, ST & s2, ST & s3)
{
	
	moveEitherDirection(s1, s2);
	if (s1.empty() && s2.empty()) { return; }
	printall("DEBUG1: ", s1, s2, s3);

	moveEitherDirection(s1, s3);
	if (s1.empty() && s2.empty()) { return; }
	printall("DEBUG2: ", s1, s2, s3);

	moveEitherDirection(s2, s3);
	if (s1.empty() && s2.empty()) { return; }
	printall("DEBUG3: ", s1, s2, s3);
}

int main() {

	ST s1, s2, s3;

	s1.push(4);
	s1.push(3);
	s1.push(2);
	s1.push(1);

	print("START", s1); print("START", s2); print("START", s3);
	bool done = false;

	int i = 0;

	while (done == false)
	{
		cout << "-------------------------" << endl;
		solution1(s1, s2, s3);
		if (s1.empty() && s2.empty()) { break; }
		i++;
		if (i > 1000) break;
	}

	print("DONE", s1); print("DONE", s2); print("DONE", s3);
	int x;
	cin >> x;
	return 0;
}

// OUTPUT

START 4 3 2 1
START
START
-------------------------
DEBUG1: 1 4 3 2
DEBUG1: 2 1
DEBUG1: 3

DEBUG2: 1 4 3
DEBUG2: 2 1
DEBUG2: 3 2

DEBUG3: 1 4 3
DEBUG3: 2
DEBUG3: 3 2 1

-------------------------
DEBUG1: 1 4
DEBUG1: 2 3
DEBUG1: 3 2 1

DEBUG2: 1 4 1
DEBUG2: 2 3
DEBUG2: 3 2

DEBUG3: 1 4 1
DEBUG3: 2 3 2
DEBUG3: 3

-------------------------
DEBUG1: 1 4
DEBUG1: 2 3 2 1
DEBUG1: 3

DEBUG2: 1
DEBUG2: 2 3 2 1
DEBUG2: 3 4

DEBUG3: 1
DEBUG3: 2 3 2
DEBUG3: 3 4 1

-------------------------
DEBUG1: 1 2
DEBUG1: 2 3
DEBUG1: 3 4 1

DEBUG2: 1 2 1
DEBUG2: 2 3
DEBUG2: 3 4

DEBUG3: 1 2 1
DEBUG3: 2
DEBUG3: 3 4 3

-------------------------
DEBUG1: 1 2
DEBUG1: 2 1
DEBUG1: 3 4 3

DEBUG2: 1
DEBUG2: 2 1
DEBUG2: 3 4 3 2

DONE
DONE
DONE 4 3 2 1

以上是关于c_cpp 河内的塔的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 以递归方式做河内塔问题的基准.n = 20来自维基百科的伪代码:https://zh.wikipedia.org/wiki/汉诺塔

河内塔是什末

河内塔游戏

河内塔

河内的线性塔

长生不老药的塔