1. Function recursion
A procedure that calls itself directly or indirectly is said to be recursive.
Advantages: Clear structure, easy to read program.
2. Analysis of the Tower of Hanoi Problem
The Tower of Hanoi problem is actually
(1) Move the n-1 pillars on pillar A to pillar B (transition of pillar C)
(2) Move the nth column on column A to C
(3) Move n-1 pillars on pillar B to C (transition of pillar A)
Repeat this process until n=1
3. The C++ code of 3 as an example
#include<iostream>
using namespace std;
void move(char a, int n,char b) {
cout << "将圆盘" << n<<"从"<<a << "移动到" << b << endl;
}
void Hanoi(int n,char a,char b,char c) {
if (n == 1) {
move(a, 1, c);
}
else {
Hanoi(n - 1, a, c, b);/*汉诺塔问题的其实就是先将n-1层的塔从塔1完整的移动到塔2,这一步就是这个过程*/
move(a, n , c);
Hanoi(n - 1, b, a, c);/*再把塔1上的n层的塔移到塔3,塔2上已经移动好的n-1层塔再次移动到塔3,这步是这个过程*/
}
}
int main() {
Hanoi(3, 'a', 'b','c');
return 0;
}
run screenshot