河内塔柜台 [英] Counter for Towers Of Hanoi
本文介绍了河内塔柜台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经为《河内的塔》游戏编写了代码.我不知道该程序执行了多少次后如何实现该计数器.任何帮助将不胜感激.
I have written a code for Towers Of Hanoi game. I don't know how to implement a counter for this program on how many times it ran. Any help will be much appreciated.
public class MainClass {
public static void main(String[] args) {
int nDisks = 3;
doTowers(nDisks, 'A', 'B', 'C');
}
public static void doTowers(int topN, char from, char inter, char to) {
if (topN == 1){
System.out.println("Disk 1 from " + from + " to " + to);
}else {
doTowers(topN - 1, from, to, inter);
System.out.println("Disk " + topN + " from " + from + " to " + to);
doTowers(topN - 1, inter, from, to);
}
}
}
推荐答案
将doTowers
的返回类型从void
更改为int
,并将返回值设置为:
Change the return type of doTowers
from void
to int
, and set the return value to:
- 如果
topN == 1
,则返回1; - 否则返回两个
doTowers()
加1的总和.
- if
topN == 1
, return 1; - else return the sum of two
doTowers()
plus 1.
逻辑类似于问题的算法.玩弄找出来吧!
The logic is similar to the algorithm of the problem. Have fun figuring it out!
您还可以使用静态全局变量,但这可以说是不好的编程风格.
You could also use a static global variable, but that's arguably bad programming style.
这篇关于河内塔柜台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文