1.递归方式
主要代码:
public static int f(int n,char a,char b,char c){
//汉诺塔
if(n==1){
System.out.println(a+"-->"+c);
number++;
return 0;
}
else{
f(n-1,a,c,b);
System.out.println(a+"-->"+c);
f(n-1,b,a,c);
number++;
}
return 0;
}
测试:
public class Text {
//汉诺塔
static int number=0;
public static void main(String[] args) {
long time1= System.currentTimeMillis();
char a='A',b='B',c='C';
System.out.println(f(17,a,b,c));
System.out.println("number: "+number);
long time2= System.currentTimeMillis();
System.out.println(time2-time1);
}
public static int f(int n,char a,char b,char c){
//汉诺塔
if(n==1){
System.out.println(a+"-->"+c);
number++;
return 0;
}
else{
f(n-1,a,c,b);
System.out.println(a+"-->"+c);
f(n-1,b,a,c);
number++;
}
return 0;
}

当n==17时;
算法耗费时间为685ms
但该函数创建了131071次(2^17-1);
第二种方式(用字符串拼接的方式改进)
用的算法还是递归,可以把汉诺塔的移动盘子的步骤记录下来到字符串中,然后如果字符串中已记录中的,则直接跳过(相当于去掉递归中重复的部分)
import static jdk.nashorn.internal.objects.NativeString.substr;
public class name {
static String str="";
static int [] count=new int[100];
static int number=0;
public static void main(String[] args) {
long time1= System.currentTimeMillis();
char a='A',b='B',c='C';
System.out.println(f(17,a,b,c));
readMethod();
System.out.println("number: "+number);
long time2= System.currentTimeMillis();
System.out.println(time2-time1);
}
public static int f(int n,char a,char b,char c){
//汉诺塔
if(n==1&&count[1]==0){
// System.out.println(a+"-->"+c);
writeMethod2(a,c);
count[1]=1;
number++;
return 0;
}
else{
if(count[n]==0) {
count[n]=1;
f(n-1,a,c,b);
// System.out.println(a+"-->"+c);
writeMethod2(a,c);
readMethod1(a,b,c);
f(n-1,b,a,c);
number++;
}
}
return 0;
}
public static void writeMethod1(String str1)
{
str=str.concat(str1);
}
public static void writeMethod2(char A,char B)
{
str=str.concat(A+"-->"+B);
}
public static void readMethod1(char A,char B,char C)
{
String str1="";
str1=substr(str,0, str.length()-5);
str1 = str1.replace(C,'M');
str1 = str1.replace(A,C);
str1 = str1.replace('M',A);
str1 = str1.replace(B,'M');
str1 = str1.replace(C,B);
str1 = str1.replace('M',C);
str=str.concat(str1);
}
public static void readMethod()
{
for (int i = 0; i < str.length(); i=i+5) {
String str1="";
str1=substr(str,i, 5);
System.out.println(str1);
}
}
}
次数减少了,但时间比上面的多了一些(可能字符串拼接效率不高吧。。。)










