汉诺塔java和python的实现

来源:互联网 发布:创世兵魂刷枪软件 编辑:程序博客网 时间:2024/06/03 19:34

汉诺塔是递归经典的应用实例,主要思想是借助中间柱,将源目标柱的套圈移到目标柱:以下为实现代码:
Java

package ms;import org.junit.Test;public class Hanoi {    @Test    public void test(){        hanoi(3,"A","B","C");    }    public void hanoi(int n, String from, String middle, String to){        if(n==1)            move(from,to);        else{            hanoi(n-1, from, to , middle);            move(from, to);            hanoi(n-1, middle, from, to);        }    }    private void move(String a, String c) {        System.out.println(a+"----->"+c);    }}

python

__author__ = 'home'def hanoi(n, src, middle, dest):    if n == 1:        move(src,dest)    else:        hanoi(n-1,src,dest,middle)        move(src,middle)        hanoi(n-1,middle,src,dest)def move(src , dest):    print(src+"--->"+dest)hanoi(3,"a","b","c")
0 0
原创粉丝点击