这个迭代的河内塔如何工作? C

时间:2010-05-20 02:37:20

标签: c iteration towers-of-hanoi

  

可能重复:
  How does this work? Weird Towers of Hanoi Solution

在浏览Google时,我发现这个有趣的解决方案是Tower Of Hanoi,它甚至不使用堆栈作为数据结构。

有人可以简单解释一下,它到底在做什么?

这个解决方案真的可以接受吗?

代码

#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号硬编码在这里做了什么?

2 个答案:

答案 0 :(得分:11)

在PSEUDOCODE中可能更容易看到:

GET NUMBER OF DISKS AS n
WHILE x BETWEEN 1 INCLUSIVE AND 1 LEFT-SHIFTED BY n BITS
    SUBTRACT 1 FROM n, DIVIDE BY 3 AND TAKE THE REMAINDER AS A
    OR x WITH x-1, ADD 1 TO THAT, DIVIDE BY 3 AND TAKE THE REMAINDER AS B
    PRINT "MOVE FROM TOWER " A " TO TOWER " B
    ADD 1 TO x

1个左移由n位基本上为2的幂,在4个磁盘的情况下为16。

If you walk through this sequence manually, you should see the progression of movement of the disks. http://library.ust.hk/images/highlights/Tower_of_Hanoi_4.gif

答案 1 :(得分:6)

这是河内之塔的二元解决方案之一,维基百科上有这个算法的详细解释 - 阅读the "Binary solution" paragraph