这个流程图你懂得,看文件数目了,大家自己分析吧。

  ④汉诺塔问题

  这是递归的超经典的例子,几乎每本程序设计书上谈到递归都会介绍。具体情景不再赘述。以我上述的方法观之:

  (1)递归的出口在于盘子数为1的时候 。

  (2)向出口逼近:如果不是1,是n ,则我们先挪动上面n-1块盘子,等上面挪完,即递归返回的时候,我们挪动底下的盘子。

  求解代码:

  [html] view plaincopyprint?

  import javax.swing.JOptionPane;

  /*

  * time:2012.12.2

  * author:王金宇

  * description:

  */

  public class Hanoi {

  private final static String from = "盘子B";

  private final static String to = "盘子C";

  private final static String mid = "盘子A";

  public static void main(String[] args) {

  String input = JOptionPane.showInputDialog("请输入你要移动的盘子数");

  int num = Integer.parseInt(input);

  Hanoi.move(num, from, mid, to);

  }

  private static void move(int num, String from2, String mid2, String to2) {

  if (num == 1) {

  System.out.println("移动盘子1 从" + from2 + "到" + to2);

  } else {

  move(num - 1, from2, to2, mid2);

  System.out.println("移动盘子" + num + " 从" + from2 + "到" + to2);

  move(num - 1, mid2, from2, to2);

  }

  }

  }

  import javax.swing.JOptionPane;

  /*

  * time:2012.12.2

  * author:王金宇

  * description:

  */

  public class Hanoi {

  private final static String from = "盘子B";

  private final static String to = "盘子C";

  private final static String mid = "盘子A";

  public static void main(String[] args) {

  String input = JOptionPane.showInputDialog("请输入你要移动的盘子数");

  int num = Integer.parseInt(input);

  Hanoi.move(num, from, mid, to);

  }

  private static void move(int num, String from2, String mid2, String to2) {

  if (num == 1) {

  System.out.println("移动盘子1 从" + from2 + "到" + to2);

  } else {

  move(num - 1, from2, to2, mid2);

  System.out.println("移动盘子" + num + " 从" + from2 + "到" + to2);

  move(num - 1, mid2, from2, to2);

  }

  }

  }