这是我使用递归解决河内塔的Java代码:
Here's my Java code for solving Tower of Hanoi using recursion:
/**here is a stack of N disks on the first of three poles (call them A, B and C) and your job is to move the disks from pole A to pole B without ever putting a larger disk on top of a smaller disk.*/ public class Hanoi { public static void main(String[] args) { playHanoi (2,"A","B","C"); } //move n disks from position "from" to "to" via "other" private static void playHanoi(int n, String from , String other, String to) { if (n == 0) return; if (n > 0) playHanoi(n-1, from, to, other); System.out.printf("Move one disk from pole %s to pole %s \n ", from, to); playHanoi(n-1, other, from, to); } }我放置打印的地方吗方法有关系?另外,我可以这样做:
Does the place I put the print method matter? Also, can I do it like this:
playHanoi(n-1, from, to, other); playHanoi(n-1, other, from, to); System.out.printf("Move one disk from pole %s to pole %s \n ", from, to);推荐答案
解决 Hanoy之塔这样的问题,只不过是定义了你想要完成工作的策略。和你的代码:
Solving Tower of Hanoy problem in this way, is nothing but defining the strategy of how you want to get the job done. And your code :
playHanoi(n-1, from, to, other); System.out.printf("Move one disk from pole %s to pole %s \n ", from, to); playHanoi(n-1, other, from, to);基本上将您的策略定义为吼叫,
Basically defines your strategy to like bellow,
您的 prinf 基本上是 2 nd步骤。
Your prinf basically does the 2 nd step.
现在,如果你写这样的代码:
Now if you write code like this:
playHanoi(n-1, from, to, other); playHanoi(n-1, other, from, to); System.out.printf("Move one disk from pole %s to pole %s \n ", from, to);然后你基本上在做:
最后从 从 移动 n 磁盘(来源)塔)到 到 (目的地塔)。
Finally move n th disk from "from" (source tower) to "to" (destination tower).
在此策略中,执行 2 步骤后(从 移动所有 n-1 磁盘)其他 到 到 ), 3 rd步骤无效(移动 n 磁盘从 从 到 到 )!因为在 Tower of Hanoy 中你不能把较大的磁盘放在较小的磁盘上!
In this strategy, after doing the 2 nd step (moving all n-1 disks from "other" to "to"), 3 rd step becomes invalid(moving n th disk from "from" to "to")! Because in Tower of Hanoy you cant put a larger disk on a smaller one!
因此,选择第二个选项(策略)会导致您采用无效策略,这就是为什么您不能这样做的原因!
So choosing the second option(strategy) leads you to an invalid strategy, thats why you can not do that!
更多推荐
河内塔递归java
发布评论