TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
C语言趣味程序百例精解之java实现(93)汉内塔

程序:
- public class Test93{
- public static void main(String args[]){
- runHanoi(4,"A","B","C");
- }
-
- public static void runHanoi(int n,char x,char y,char z){
- if(n==1){
- System.out.println("Move top disk from peg "+x+" to peg "+z);
- }else{
- runHanoi(n-1,x,z,y);
- runHanoi(1,x,y,z);
- runHanoi(n-1,y,x,z);
- }
- }
- }
- 求解4个盘的输出是:
- Move top disk from peg A to peg B
- Move top disk from peg A to peg C
- Move top disk from peg B to peg C
- Move top disk from peg A to peg B
- Move top disk from peg C to peg A
- Move top disk from peg C to peg B
- Move top disk from peg A to peg B
- Move top disk from peg A to peg C
- Move top disk from peg B to peg C
- Move top disk from peg B to peg A
- Move top disk from peg C to peg A
- Move top disk from peg B to peg C
- Move top disk from peg A to peg B
- Move top disk from peg A to peg C
- Move top disk from peg B to peg C
复制代码
源码下载:http://file.javaxxz.com/2014/11/25/000423984.zip |
|