C - 汉诺塔 - 使用数组显示算法每次迭代的每个 Hook 的内容

标签 c arrays algorithm

我是编程新手,目前我的任务之一是成功编写解决汉诺塔问题的程序。我已经有一个程序已经在运行,但是,我希望能够在每次迭代后看到每个 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)内容的可能方法。

  1. 使用节点的双向链表,其中每个节点包含关联磁盘的编号
  2. 决定如何显示链接列表内容
  3. 移动磁盘就变成从源链表中删除第一个节点并将其插入到目标链表的第一个位置
  4. 请注意,任何特定的链表都可以包含 0 到 n 个节点。

关于C - 汉诺塔 - 使用数组显示算法每次迭代的每个 Hook 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35349576/

相关文章:

c - 清理程序时出现段错误

c++ - 给指针赋值抛出异常

JavaScript 数组访问元素

java - Big O - 适合新手

algorithm - 如何在 Karmarkar-Karp 启发式多路分区算法中重建分区?

c - Unresolved external 因素 (LNK1120)

c - 除非打印字符串,否则程序崩溃

java - 使用数组排序

arrays - 如何检查给定单元格是否包含任何数字?

algorithm - 我的网页排名总和收敛于 0.9