我用Python验证了一下该程序是否会出现不满足规则(4)的情况,验证代码如下:
def hanoi(n, _from, to, tmp): # 把n个圆盘从_from移动到to, 可以暂时移动到tmp
if n <= 0:
return
elif n == 1:
to.append(_from.pop())
if (len(to) >= 2) and ((to[-2] - to[-1]) % 2 == 0): # 如果检测到同色圆盘叠在一起的情况,则提示出错并结束移动
print('Error!')
return
else:
hanoi(n - 1, _from, tmp, to)
to.append(_from.pop())
if (len(to) >= 2) and ((to[-2] - to[-1]) % 2 == 0): # 如果检测到同色圆盘叠在一起的情况,则提示出错并结束移动
print('Error!')
return
hanoi(n - 1, tmp, to, _from)
towerA = []
towerB = []
towerC = []
for n in range(1, 27): # 验证圆盘数量为从1到25的情况
for i in range(1, n):
towerA.append(i)
towerA.reverse() # 初始时A塔座所存放的元素为[n-1, n-2, n-3, ..., 2, 1]
hanoi(n - 1, towerA, towerB, towerC) # 把A塔座上的圆盘移动到B塔座,可暂时移动到C塔座
print(towerA) # 显示移动完成后三个塔座的状态
print(towerB)
print(towerC)
towerA.clear()
towerB.clear()
towerC.clear()
验证结果截图如下,这表明不会产生不满足规则(4)的情况。
该程序的思想是先把塔座A上前n-1个圆盘移动到塔座C,然后把第n个圆盘从A移动到B,最后把这n-1个从塔座C移动到塔座B
#include <stdio.h>
void hanoi(int n, char from, char to, char tmp) //把n个圆盘从from塔座移动到to塔座,可以暂时移动到tmp塔座
{
char filename_output[] = "output.txt";
FILE* f_out = NULL;
f_out = fopen(filename_output, "a");
if (f_out == NULL)
{
printf("Open %s error!", filename_output);
return;
}
if (n <= 0)
return;
else if (n == 1)
{
fprintf(f_out, "1 %c %c\n", from, to);
fclose(f_out);
}
else
{
hanoi(n - 1, from, tmp, to); //把前n-1个圆盘从from塔座移动到tmp塔座
fprintf(f_out, "%d %c %c\n", n, from, to); //把第n个圆盘从from塔座移动到to塔座
fclose(f_out);
hanoi(n - 1, tmp, to, from); //把上述n-1个圆盘从tmp塔座移动到to塔座
}
}
int main(void)
{
FILE* f_in = NULL;
char filename_input[] = "./test/hanoi0.in";
int n;
f_in = fopen(filename_input, "r");
if (f_in == NULL)
{
printf("Open %s error!", filename_input);
}
fscanf(f_in, "%d", &n);
hanoi(n, 'A', 'B', 'C');
return 0;
}
程序的运行结果如下: