Experiment 3-1.7 Non-recursive implementation of the Tower of Hanoi

Solve the Towers of Hanoi non-recursively (loop) with the help of a stack.

First take out the very typical recursive version:

# include <iostream>
void Hanoi(char from, char to, char tmp, int n)
{
    
    
	// from: 起始柱名 to:目标柱名 tmp:辅助柱名 n:个数
	if (n == 0) return;

	Hanoi(from, tmp, to, n - 1);
	std::cout << from << " -> " << to << '\n';
	Hanoi(tmp, to, from, n - 1);
}

int main(void)
{
    
    
	Hanoi('A', 'C', 'B', 3);
	return 0
}

The simulated recursion is stacked layer by layer in the stack area during operation, and a stack is required to store the information of the calling function and the called function. Information, encapsulated with a structure.

# include "Stack.h"

struct information {
    
    
	char from;
	char to;
	char tmp;
	int n;
};

void Hanoi(char from, char to, char tmp, int n)
{
    
    
	Stack<information> s;
	s.push(information{
    
     from, to, tmp, n });
	while (!s.empty())
	{
    
    
		information i = s.pop();
		if (i.n-1 > 0) s.push(information{
    
     i.from, i.tmp, i.tmp, i.n-1 });
		std::cout << i.from << " -> " << i.to << '\n';
		if (i.n - 1 > 0) s.push(information{
    
     i.tmp, i.to, i.from, i.n-1 });
	}
}

The significance of this conversion is to save space. In fact, the space complexity in the asymptotic sense of the two is the same. The part saved comes from the fact that every time the recursion needs to be nested, the information will be raised once when the recursion is called in the stack area, and it will return when it reaches the deepest point . , so the constant of the space complexity is large. And tail recursion, every time a function is called, it will be executed , and the position occupied by the current function in the stack area will be eliminated. So the constant of space complexity will get smaller.

Guess you like

Origin blog.csdn.net/weixin_45339670/article/details/131880464