我是编程新手,目前我的任务之一是成功编写解决汉诺塔问题的程序。我已经有一个程序已经在运行,但是,我希望能够在每次迭代后看到每个 Hook 包含的内容,但是我不太确定如何在这里实现数组/二维数组。
这是我到目前为止的代码:
#include <stdio.h>
void towerOfHanoi(int numberOfDisks, char source, char destination, char aux)
{
char ArrayA[100];
char ArrayB[100];
char ArrayC[100];
if (numberOfDisks == 1)
{
printf("Move disk 1 from peg %c to peg %c \n", source, destination);
return;
}
towerOfHanoi(numberOfDisks - 1, source, aux, destination);
printf("Move disk %d from peg %c to peg %c\n", numberOfDisks, source, destination);
towerOfHanoi(numberOfDisks - 1, aux, destination, source);
}
int main()
{
int numberOfDisks;
char startingPoint;
printf("Enter the amount of Disks: \n");
scanf("%d", &numberOfDisks);
printf("Which peg would you like to start from? (A rightside, B centre, C, leftside\n");
scanf("\n%c", &startingPoint);
if (startingPoint == 'A')
{
printf("The sequence of moves invloved in the tower of hanoi are: \n");
towerOfHanoi(numberOfDisks, 'A', 'B', 'C');
}
else if (startingPoint == 'B')
{
printf("The sequence of moves invloved in the tower of hanoi are: \n");
towerOfHanoi(numberOfDisks, 'B', 'A', 'C');
}
else if (startingPoint == 'C')
{
printf("The sequence of moves invloved in the tower of hanoi are: \n");
towerOfHanoi(numberOfDisks, 'C', 'A', 'B');
}
return 0;
}
最佳答案
一种能够显示每个(A、B、C)内容的可能方法。
- 使用节点的双向链表,其中每个节点包含关联磁盘的编号
- 决定如何显示链接列表内容
- 移动磁盘就变成从源链表中删除第一个节点并将其插入到目标链表的第一个位置
- 请注意,任何特定的链表都可以包含 0 到
n
个节点。
关于C - 汉诺塔 - 使用数组显示算法每次迭代的每个 Hook 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35349576/