当前位置: 移动技术网 > IT编程>开发语言>Java > java数据结构和算法学习之汉诺塔示例

java数据结构和算法学习之汉诺塔示例

2019年07月22日  | 移动技术网IT编程  | 我要评论

复制代码 代码如下:

package com.tiantian.algorithms;
/**
 *    _|_1              |                |
 *   __|__2             |                |
 *  ___|___3            |                |            (1).把a上的4个木块移动到c上。
 * ____|____4           |                |
 *     a                b                c
 *
 *     |                |                |
 *     |               _|_1              |
 *     |              __|__2             |            要完成(1)的效果,必须要把1、2、3木块移动到b,这样才能把4移动到c
 * ____|____4        ___|___3            |            如:代码中的“调用(xx)”
 *     a                b                c
 *    
 *     |                |                |
 *     |               _|_1              |
 *     |              __|__2             |            此时,题目就变成了把b上的3个木块移动到c上,回到了题目(1)
 *     |             ___|___3        ____|____4        如:代码中的“调用(yy)”
 *     a                b                c
 *    
 *     然后循环这个过程
 *
 * @author wangjie
 * @version 创建时间:2013-3-4 下午4:09:53
 */
public class hanoitowertest {
    public static void main(string[] args) {
        dotowers(4, 'a', 'b', 'c');
    }

    public static void dotowers(int topn, char from, char inter, char to){
        if(topn == 1){
            system.out.println("最后把木块1从" + from + "移动到" + to);
        }else{
            dotowers(topn - 1, from, to, inter); // 调用(xx)
            system.out.println("把木块" + topn + "从" + from + "移动到" + to);
            dotowers(topn - 1, inter, from ,to); // 调用(yy)
        }

    }
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网