河内之塔:递归算法

编程入门 行业动态 更新时间:2024-10-23 22:25:18
本文介绍了河内之塔:递归算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

尽管我对理解递归没有任何问题,但是我似乎无法将自己的头围在河内塔问题的递归解决方案上.这是来自维基百科的代码:

Although I have no problem whatsoever understanding recursion, I can't seem to wrap my head around the recursive solution to the Tower of Hanoi problem. Here is the code from Wikipedia:

procedure Hanoi(n: integer; source, dest, by: char); Begin if (n=1) then writeln('Move the plate from ', source, ' to ', dest) else begin Hanoi(n-1, source, by, dest); writeln('Move the plate from ', source, ' to ', dest); Hanoi(n-1, by, dest, source); end; End;

我了解基本情况以及将问题分解成小块直到可以移动单个磁盘的概念.但是,我无法弄清楚在非基本情况下这两个递归调用是如何一起工作的.也许有人可以帮助我?谢谢.

I understand the base case and the concept of breaking the problem into smaller pieces until you are able to move a single disk. However, I can't figure out how the two recursive calls in the non-base case work together. Perhaps someone can help me out? Thanks.

推荐答案

实际上,部分从何处您采用的代码也提供了解释:

Actually, the section from where you took that code offers an explanation as well:

要将n张光盘从钉A移到钉C:

To move n discs from peg A to peg C:

  • 将n−1个光盘从A移动到B.这使#n光盘独自留在钉A上
  • 将光盘#n从A移到C
  • 将n-1个光盘从B移到C,因此它们位于#n光盘上
  • 很明显,您首先必须删除 n -1个光盘才能访问第 n 个光盘.而且您必须首先将它们移动到另一个钉子,而不是想要整个塔楼出现的地方.

    It's pretty clear that you first have to remove n − 1 discs to get access to the nth one. And that you have to move them first to another peg than where you want the full tower to appear.

    帖子中的代码除了光盘数量外,还包含三个参数: source 钉, destination 钉和 temporary 钉可以在其间存储哪些光盘(每个大小 n − 1的光盘都适合).

    The code in your post has three arguments, besides the number of discs: A source peg, a destination peg and a temporary peg on which discs can be stored in between (where every disc with size n − 1 fits).

    递归实际上发生了两次,一次在writeln之前,一次在之后. writeln之前的那一个会将 n − 1个光盘移动到临时钉上,并使用目标钉作为临时存储(递归调用中的参数顺序不同).之后,剩余的光盘将被移动到目标钉,然后第二次递归通过将 n -1个塔从临时钉移动到目标钉,从而迫使整个塔的移动光盘 n.

    The recursion happens actually twice, there, once before the writeln, once after. The one before the writeln will move n − 1 discs onto the temporary peg, using the destination peg as temporary storage (the arguments in the recursive call are in different order). After that, the remaining disc will be moved to the destination peg and afterwards the second recursion compeltes the moving of the entire tower, by moving the n − 1 tower from the temp peg to the destination peg, above disc n.

    更多推荐

    河内之塔:递归算法

    本文发布于:2023-11-30 03:09:13,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1648522.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:递归   河内   算法

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!