可能重複:
How does this work? Weird Towers of Hanoi Solution河內迭代塔如何工作? ç
雖然谷歌衝浪,我發現這個有趣的解決方案,以漢諾塔它甚至沒有用到堆棧數據結構。
有人可以簡單地解釋我,它究竟在做什麼?
這個解決方案真的可以接受嗎?
代碼
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, x;
printf("How many disks?\n");
scanf("%d", &n);
printf("\n");
for (x=1; x < (1 << n); x++)
printf("move from tower %i to tower %i.\n",
(x&x-1)%3, ((x|x-1)+1)%3);
return 0;
}
更新:什麼是硬編碼數字3在這裏幹什麼?
它使用標準的3根棒。 – 2010-05-20 02:42:25
它報告正確的移動順序嗎?如果是這樣,它就會起作用,而且沒有理由不接受它。但是,在提供它作爲家庭作業的解決方案之前,您需要了解它,否則,如果您被要求解釋它,您將會遇到麻煩,因爲它可能與正常情況非常不同。 – 2010-05-20 02:44:28
這不是我的作業。我只是意外地發現了這個算法,並且想知道它是如何工作的。 – TCM 2010-05-20 02:48:42