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

发布于 2024-09-02 02:04:52 字数 696 浏览 2 评论 0原文

可能的重复:
这是如何工作的?奇怪的河内塔解决方案

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

谁能简单地解释一下我,它实际上在做什么?

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

代码

#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 在这里做什么?

Possible Duplicate:
How does this work? Weird Towers of Hanoi Solution

While surfing Google, i found this interesting solution to Tower Of Hanoi which doesn't even use stack as data structure.

Can anybody explain me in brief, what is it actually doing?

Are this solution really acceptable?

Code

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

Update: What is the hard-coded number 3 doing in here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

被你宠の有点坏 2024-09-09 02:04:52

在伪代码中可能更容易看出:

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 的 n 次方,在 4 个磁盘的情况下为 16。

如果您手动执行此序列,您应该会看到圆盘移动的进度。 http://library.ust.hk/images/highlights/Tower_of_Hanoi_4.gif

Might be easier to see in 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 LEFT SHIFTED BY n BITS is basically 2 to the power of n, 16 in the case of 4 disks.

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

中性美 2024-09-09 02:04:52

它是汉诺塔的二进制解决方案之一,维基百科上有该算法的详细说明 - 阅读 “二元解决方案”段落

It is one of the binary solutions to Tower of Hanoi, there is a detailed explanation of this algorithm on Wikipedia - read the "Binary solution" paragraph.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文