您的位置:首页 > 编程语言 > Java开发

汉诺塔问题——Java详细算法分析

2017-08-09 16:30 302 查看
大一讲c++语言时就讲过汉诺塔问题,但是博主的大一跟广大人民群众一样几乎在梦游。现在要大三了,面临的就业和考研的压力得逼自己一下了,其实汉诺塔问题有很多语言都可以实现,但是毕竟现在大头还在Java所以用Java来解决一下,废话不多说直接干货吧。
像这种有规律的问题,博主建议大家每一种情况都列出来,再找规律。


public class Hanoi {

/**
* @param args
* @author AnonyJoker
* 汉诺塔问题:有三个柱子A,B,C,A放入N个盘子,并且盘子在柱子中从大到小依次向上小盘子不能在大盘子上,求把A中的盘子移到C中最少移动几次,如何移动。注意每次只能一个
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//定义三个柱子
String a = "A";
String b = "B";
String c = "C";
//移动的次数
int total = 0;
//第一种情况:A中只有一个盘子
System.out.println(a + "移到" + c );
total ++;
System.out.println("移动了" + total + "次");
//第二种情况:A中有两个盘子
System.out.println(a + "移到" + b );
total ++;
System.out.println(a + "移到" + c );
total ++;
System.out.println(b + "移到" + c );
total ++;
System.out.println("移动了" + total + "次");
//第三种情况:A中有三个盘子
System.out.println(a + "移到" + c );
total ++;
System.out.println(a + "移到" + b );
total ++;
System.out.println(c + "移到" + b );
total ++;
System.out.println(a + "移到" + c );
total ++;
System.out.println(b + "移到" + a );
total ++;
System.out.println(b + "移到" + c );
total ++;
System.out.println(a + "移到" + c );
total ++;
System.out.println("移动了" + total + "次");
//第四种情况:A中有四个盘子
System.out.println(a + "移到" + b );
total ++;
System.out.println(a + "移到" + c );
total ++;
System.out.println(b + "移到" + c );
total ++;
System.out.println(a + "移到" + b );
total ++;
System.out.println(c + "移到" + a );
total ++;
System.out.println(c + "移到" + b );
total ++;
System.out.println(a + "移到" + b );
total ++;
System.out.println(a + "移到" + c );
total ++;
System.out.println(b + "移到" + c );
total ++;
System.out.println(b + "移到" + a );
total ++;
System.out.println(c + "移到" + a );
total ++;
System.out.println(b + "移到" + c );
total ++;
System.out.println(a + "移到" + b );
total ++;
System.out.println(a + "移到" + c );
total ++;
System.out.println(b + "移到" + c );
total ++;
System.out.println("移动了" + total + "次");
}

}


汉诺塔问题就是把A柱上的N-1个盘子经过C移动到B,再把A上的最大的盘子移到C,而B上的N-1再类似上述步骤递归循环移到C上。
改进后的代码如下:


package com.test._1;

public class Hanoi_s {

/**
* @param args
* @author AnonyJoker
* 经过分析得出规律
* @total 移动的总次数
* a代表起点,b代表中转点,c是终点
*/
int total = 0;

public int getTotal() {
return total;
}

public void setTotal(int total) {
this.total = total;
}
private void move(String a,String c){
System.out.println("从" + a + "到" + c);
total ++;
}

public void hanoi(int n ,String a,String b,String c){
if(n == 1){
move(a,c);
}else{
hanoi(n-1,a,c,b);
move(a,b);
hanoi(n-1,b,a,c);
}
}

public static void main(String[] args) {
// TODO Auto-generated method stub
Hanoi_s hanoi = new Hanoi_s();
hanoi.hanoi(3, "A", "B", "C");
System.out.println(hanoi.getTotal());

}

}


汉诺塔问题本身并没有什么难度,主要利用的就是递归循环这个点,但是刚开始写代码时想的过程是特别痛苦的,特别是对于博主这种从小找规律就直接过的人来说更是难受。但如果放弃就肯定一直不会,只要自己想做就没有不会的东西。只要耐下心来分析,肯定会的。

这是博主第一次写博客,感觉写的有些拖沓,而且问题也没怎么讲清楚。有问题底下评论,大家一起进步。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 算法-java