首页 > 解决方案 > Tower of Hanoi - User is moving disks (c)

问题描述

I'm currently trying to make a c program that first asks user inputs the number of disks, and then the user is allowed to move the disks freely.
However, it must have the rules of the original Tower of Hanoi, such as the bigger disks cannot be placed over smaller ones.
Also, the poles are '0, 1, 2'

For example,

input : 5
output :
0: 5 4 3 2 1
1: x
2: x

input : 0 1
output :

0: 5 4 3 2
1: 1
2: x

input : 3 3
program ends because there is no pole 3

I would like to get a hint? sort of like a way I can start coding.
Thanks!

标签: c

解决方案


您可以制作代表 3 个极点的二维数组。

获取用户输入并初始化

arr[2][number] = {0};
for(i=0; i<number; i++){
    arr[0][i] = number-i;
}

并启动一个循环,帮助用户输入 2 个数字并操作移动。您需要检查几个条件,例如

  1. 如果 k > l, arr[x][k] < arr[x][l] 其中 x, k, l 是真数
  2. 如果输入不是正确的数字(比如你​​的例子)

也许代码可以如下所示。

scanf("%d %d", &n1, &n2);
while(n1<3 && n1>=0 && n2 <= number &&n2 > 0){
    /// deleteDisk: find last component which is not zero and make it zero and return deleted disk size
    disk = deleteDisk(arr, n1);    
    /// addDisk: change first zero to disk, return 0 if violates condition 1
    err = addDisk(arr, n2, disk);
    if (err == 0)
        break;
    /// arrayPrint: print 2d array til zero
    arrayPrint;
    scanf("%d %d", &n1, &n2);
}

推荐阅读