C++ learning record-simple recursive call example

table of Contents


Idea : Recursion mainly solves the problem similar to a kind of "mock doll": when a complex problem can be reduced by the same law, and there is a known situation in the end, recursion can be considered.
For example, the Tower of Hanoi is decreasing layer by layer. When the number of plates finally decreases to 1, it is only necessary to move the plate from the initial position to the target position, without passing through the intermediate position.

1. Tower of Hanoi

The point is that there is a clear result at the end of the recursion, rather than an infinite "mock doll". . .

#include <iostream>
using namespace std;

int m;		//计数

void move(char src, char goal)
{
    
    
	cout << src << " -> " << goal << endl;
	m += 1;
}

void hanio(int n, char src='A', char middle='B', char goal='C')
{
    
    
	if (n == 1)		//递归的终点
		move(src, goal);
	else{
    
    
		hanio(n - 1, src, goal, middle);	//以 前n-1盘子为整体移到中间,
		move(src, goal);					//将剩余的一个移到目标位置,
		hanio(n - 1, middle, src, goal);	//再将n-1盘子为整体移到目标位置即可。
	}
}

int main()
{
    
    
	int n;
	m = 0;
	cout << "输入盘子个数:" << endl;
	cin >> n;
	cout << "结果如下:" << endl;
	hanio(n);
	cout << "所需步骤个数为:" << m << endl;
	return 0;
}

operation result
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45371989/article/details/108328184