社区应用 最新帖子 精华区 社区服务 会员列表 统计排行
  • 854阅读
  • 0回复

汉诺塔算法的非递归实现java源代码

楼层直达
wwc
级别: 光盘见习
发帖
1
飞翔币
335
威望
8
飞扬币
351
信誉值
0
— 本帖被 小妖 从 飞扬资讯 移动到本区(2008-10-02) —
//#######################################################################
//# Author: chaos
//# Created Time: 2008-10-1 14:20:51
//# File Name: hanoi.java
//# Description:
//#######################################################################

import java.io.IOException;
import java.io.InputStream;

public class hanoi{
    static int N = 0;
public static void han(int height){
int fromPole, toPole, Disk;
    int[] BitStr = new int[height];
    int[] Hold  = new int[height];
    char Place[]  = {'A', 'B', 'C'};
    int i, j, temp;
    for (i=0; i < height; i++)
    {
        BitStr = 0;
        Hold = 1;
    }
    temp = 3 - (height % 2);
    int TotalMoves = (1 << height) - 1;
    for (i=1; i <= TotalMoves; i++)
    {
        for (j=0 ; BitStr[j] != 0; j++)
        {
            BitStr[j] = 0;
        }
        BitStr[j] = 1;
    for(int k=0;k<BitStr.length;k++)
        System.out.print(BitStr[k]+" ");
    System.out.print("    ");
    for(int k=0;k<Hold.length;k++)
    System.out.print(Hold[k]+" ");
        Disk = j+1;
        if (Disk == 1)
        {
            fromPole = Hold[0];
            toPole = 6 - fromPole - temp;
            temp = fromPole;
        }
        else
        {
            fromPole = Hold[Disk-1];
            toPole = 6 - Hold[0] - Hold[Disk-1];
        }
    System.out.println("disk:"+Disk+"  "+ Place[fromPole-1]+"-->"+ Place[toPole-1]);
    N++;
        Hold[Disk-1] = toPole;
    }
}
public static void main(String[] args){
    //int n=Integer.parseInt(args[0]);
    System.out.print("输入汉诺塔层数: ");
    InputStream is=System.in;
    byte[] bs=new byte[50];
    try {
            is.read(bs);
        } catch (IOException e) {
            e.printStackTrace();
        }
    int n=Integer.parseInt(new String(bs).trim());
    long now = System.currentTimeMillis();
    han(n);
    System.out.print("needing: "+N+"步 ");
    System.out.println(System.currentTimeMillis()-now+" ms");
   
}
}