欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-24 08:16:30
复制代码 代码如下:package com.tiantian.algorithms;/** *    _|_1  ...

复制代码 代码如下:

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)
        }

    }
}