C - 河内塔 - 使用数组显示算法每次迭代的每个peg的内容

时间:2016-02-11 20:38:45

标签: c arrays algorithm

我是编程新手,目前我的任务之一就是成功为河内塔问题编写程序。我已经有一个程序已经工作但是,我希望能够在每次迭代后看到每个peg包含的内容,但是我不太确定如何在这里实现数组/ 2D数组。

到目前为止,这是我的代码:

#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;
}

1 个答案:

答案 0 :(得分:0)

one possible way to be able to display the contents of each of (A,B,C).

  1. use doubly linked lists of nodes where each node contains the number of the associated disk
  2. decide how to display the linked list contents
  3. moving a disk then becomes removing the first node from the source linked list and inserting it into the first position of the destination linked list
  4. Notice that any specific linked list could contain anywhere from 0 to function Forward(){ xxxx[arrayPosition].className = "thumb"; mm[arrayPosition].className = "yyy"; if((arrayPosition == xxxx.length - 1)|| (arrayPosition == 0)){ arrayPosition = 0; }else{ arrayPosition = arrayPosition + 1; } xxxx[arrayPosition].className = "thumb active"; mm[arrayPosition].className = "yyy active"; } nodes.