Recursive function-Tower of Hanoi
-
Definition: Call yourself directly or indirectly within the function.
Key points:
When defining a recursive function, you must determine an "end condition"! ! !
Use occasion:
Dealing with some particularly complex problems, it is difficult to solve directly.
However, there can be ways to make this problem simpler (convert it into a simpler problem)
-
Use Inception to help us understand recursive functions
-
Disadvantages of recursive functions: low performance! ! !
In actual development, it is rarely used!
Use recursion to solve the Tower of Hanoi problem
-
Tower of Hanoi
Rule: The middle stick can be used as an assistant, but only one stick can be moved at a time, and the big stick cannot be placed on the small one.
Use the program to solve this problem:
#include <stdio.h>
void hanoi(int n, char pillar_start[], char pillar_mid[], char pillar_end[]) {
if (n == 1) {
printf("从%s移动到%s\n", pillar_start, pillar_end);
return;
}
hanoi(n - 1, pillar_start, pillar_end, pillar_mid);
printf("从%s移动到%s\n", pillar_start, pillar_end);
hanoi(n - 1, pillar_mid, pillar_start, pillar_end);
}
int main(void) {
char name1[] = "A柱";
char name2[] = "B柱";
char name3[] = "C柱";
int n = 3; //盘子数
hanoi(3, name1, name2, name3);
return 0;
}