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); } } }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/10775.html