汉诺塔算法java实现
2018-07-20 来源:open-open
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class HanRuoTa {
/**
* 汉诺塔算法
*/
public static void main(String[] args) {
int n =0;
BufferedReader buf;
buf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入盘数:");
try {
n = Integer.parseInt(buf.readLine());
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
HanRuoTa hanoi = new HanRuoTa();
hanoi.move(n, 'A', 'B', 'C');
}
/**
* 采用递归的算法去实现
*/
public void move(int n,char a,char b,char c){
if(n == 1)
System.out.println("盘 " + n + " 由 " + a + " 移至 " + c);
else {
move(n - 1, a, c, b);
System.out.println("盘 " + n + " 由 " + a + " 移至 " + c);
move(n - 1, b, a, c);
}
}
}
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
最新资讯
热门推荐