汉诺塔算法--递归实现

汉诺塔算法--递归实现

public class Hanoic {

 private static final String DISK_B = "diskB";
 private static final String DISK_C = "diskC";
 private static final String DISK_A = "diskA";
 static String from = DISK_A;
 static String to = DISK_C;
 static String mid = DISK_B;

 public static void main(String[] args) {
    int num = 3;
    move(num, from, mid, to);
 } 
private static void move(int num, String from2, String mid2, String to2) {
  if (num == 1) {
   System.out.println("move disk 1 from " + from2 + " to " + to2);
  } else {
   // 将num-1块盘子搬走
   move(num - 1, from2, to2, mid2);
   // 将最后一块(num)块盘子搬到目的地
   move(num, from2, to2);
   // 将num-1块盘子搬回
   move(num - 1, mid2, from2, to2);
  }

 }
 
 private static void move(int cur, String from, String to) {
  System.out.println("move disk " + cur + " from " + from + " to "
    + to);
 }
}

你可能感兴趣的:(汉诺塔算法--递归实现)