实现汉诺问题步骤推演,注意要用到递归函数,并给出C语言代码
时间: 2024-05-15 22:14:45 浏览: 5
好的,我准备开始回答问题了。
以下是C语言代码实现汉诺问题步骤推演,注意使用递归函数:
```
#include <stdio.h>
void hanoi(int n, char source, char target, char temp) {
if (n == 1) {
printf("Move disk 1 from %c to %c\n", source, target);
return;
}
hanoi(n - 1, source, temp, target);
printf("Move disk %d from %c to %c\n", n, source, target);
hanoi(n - 1, temp, target, source);
}
int main() {
int n = 3; // 填入汉诺塔的层数
hanoi(n, 'A', 'C', 'B');
return 0;
}
```
以上代码基于经典的递归思想,实现了汉诺问题的求解。如果有其他问题,可以再问我哦。
相关问题
递归方法实现汉诺塔问题的C语言代码
当然,下面是递归方法实现汉诺塔问题的C语言代码:
```
#include <stdio.h>
void move(int n, char a, char b, char c);
void move(int n, char a, char b, char c)
{
if(n == 1)
printf("%c-->%c\n", a, c);
else
{
move(n - 1, a, c, b);
printf("%c-->%c\n", a, c);
move(n - 1, b, a, c);
}
}
int main()
{
int n;
printf("Please input the number of disks: ");
scanf("%d", &n);
printf("The steps of moving %d disks:\n", n);
move(n, 'A', 'B', 'C');
return 0;
}
```
非递归方法实现汉诺塔问题的C语言代码
下面是非递归方式实现汉诺塔问题的C语言代码:
```C
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 1000
#define ElemType int
//定义栈结构
typedef struct {
int top;
ElemType A[MaxSize];
} Stack;
//初始化栈
void InitStack(Stack *S) {
S->top = 0;
}
//判断栈是否为空
int IsEmptyStack(Stack *S) {
return S->top == 0;
}
//判断栈是否已满
int IsFullStack(Stack *S) {
return S->top == MaxSize;
}
//入栈
void Push(Stack *S, ElemType e) {
if (IsFullStack(S)) {
printf("Stack is full!\n");
exit(1);
} else {
S->A[S->top++] = e;
}
}
//出栈
ElemType Pop(Stack *S) {
if (IsEmptyStack(S)) {
printf("Stack is empty!\n");
exit(1);
} else {
return S->A[--S->top];
}
}
//非递归方式实现汉诺塔
void Hanoi(int n) {
Stack *S = (Stack *) malloc(sizeof(Stack));
InitStack(S);
int i;
for (i = n; i >= 1; i--) {
Push(S, i);
}
int j;
ElemType x, y;
for (j = 1; j <= (1 << n) - 1; j++) {
if (j % 3 == 1) {
x = Pop(S);
printf("%d: Move disk %d from A to C\n", j, x);
Push(S, x);
} else if (j % 3 == 2) {
y = Pop(S);
printf("%d: Move disk %d from A to B\n", j, y);
x = Pop(S);
printf("%d: Move disk %d from A to C\n", j, x);
Push(S, y);
Push(S, x);
} else {
y = Pop(S);
printf("%d: Move disk %d from B to C\n", j, y);
Push(S, y);
}
}
free(S);
}
//主函数
int main() {
int n = 3;
Hanoi(n);
return 0;
}
```
此代码使用栈实现了汉诺塔问题的非递归解法。每次移动都是在栈中进行的,而不是通过递归调用函数实现。当然,这只是一种特殊的解法,使用递归调用函数依然是汉诺塔问题的标准解法。