首页 > 试题广场 >

从前有三座塔,分别命名为 X、Y、Z。其中在 Z 这座塔上,

[问答题]
从前有三座塔,分别命名为 X、Y、Z。其中在 Z 这座塔上,有个一定数量个盘子,比如 N 个,每个盘子 的直径都不相同,并且按自下往上、从大到小排列。现在想把 Z 塔上的盘子都移动到 X 塔上,并且移动之后, X 塔上盘子的顺序和 Z 原来的顺序是一样的。在移动过程中,每次只能移动一个盘子;Y 也可以放盘子,但是 盘子无论放在哪座塔上,盘子必须按自下往上、从大到小排列。
应该是基础的汉诺塔问题吧

void hanoi(int n, char X, char Y, char Z)
{
    if(n>0)
    {
         hanoi(n-1, Z, X, Y);
         cout<<Z<<"-->"<<X<<endl;
         hanoi(n-1, Y, X, Z);
    }
}
 

发表于 2015-09-14 09:43:07 回复(0)
简单的汉诺塔问题:
public class HanNoidTower {
    /**
     * 
     * @param z templates "from"
     * @param x templates "to"
     * @param y templates "through"
     * @param n move top n templates
     */
    public void move(char z ,char x, char y, int n){
        if(n==0)
            return ;
        move(z,y,x,n-1);
        System.out.println(z+"->"+x);
        move(y,x,z,n-1);
    }
    public static void main(String[] args){
        HanNoidTower hanNoidTower = new HanNoidTower();
        hanNoidTower.move('z','x','y',3);
    }
}

发表于 2015-02-12 23:19:51 回复(1)
import java.util.Scanner;


public class Hanruota {

    public static void get(int n,String z,String y,String x){
    //如果n==1直接从Z柱子移到X柱子
    if(n==1)
    System.out.println(n+" " +z+"-->"+x);
    else{
    get(n-1,z,x,y);
    System.out.println(n+" "+z+"-->"+x);      
    get(n-1,y,z,x);
    }
    }
public static void main(String[] args) {
           String x="x",y="y",z="z";
           int n;
           Scanner sc=new Scanner(System.in);
           n=sc.nextInt();
                    get(n,z,y,x);
}

}

发表于 2015-02-12 17:02:08 回复(0)