java数据结构与算法-递归解决汉诺塔问题

一、主函数调用如下

int nDisks=3;//塔层数,即盘数
tower_recursion(nDisks,'A','B','C');

二、递归解决汉诺塔

    /**
     * 递归解决汉诺塔问题
     * @param topN 第几层盘子
     * @param from 原柱
     * @param inter 临时柱
     * @param to 目标柱
     */
    private void tower_recursion(int topN,char from,char inter,char to){
        if(topN==1)//若为塔底(最底层的盘子),即则将其直接挪到目标柱
            Log.v(TAG,"Disk 1 from "+from+" to "+to);
        else{
            tower_recursion(topN-1,from,to,inter);//先放到临时柱
            Log.v(TAG,"Disk "+topN+" from "+from+" to "+to);
            tower_recursion(topN-1,inter,from,to);//然后从临时柱放到目标柱
        }
    }

打印日志如下:

08-15 10:21:54.180 25472-25472/com.tool.wpn.quicksort V/MainActivity: Disk 1 from A to C
08-15 10:21:54.180 25472-25472/com.tool.wpn.quicksort V/MainActivity: Disk 2 from A to B
08-15 10:21:54.180 25472-25472/com.tool.wpn.quicksort V/MainActivity: Disk 1 from C to B
08-15 10:21:54.180 25472-25472/com.tool.wpn.quicksort V/MainActivity: Disk 3 from A to C
08-15 10:21:54.180 25472-25472/com.tool.wpn.quicksort V/MainActivity: Disk 1 from B to A
08-15 10:21:54.180 25472-25472/com.tool.wpn.quicksort V/MainActivity: Disk 2 from B to C
08-15 10:21:54.180 25472-25472/com.tool.wpn.quicksort V/MainActivity: Disk 1 from A to C


源码下载地址:点击打开链接

你可能感兴趣的:(数据结构与算法)