1栈和队列--用栈来求解汉诺塔问题

时间:2020-11-26 11:04:17

修改游戏规则,只能移动一步,不能直接从最左侧到最右侧,必须经过中间过度。
当有N层塔时,打印最优移动过程最优总步数

  1. 递归方法
  2. 非递归方法,用栈来模拟三个塔
  1. 递归方法
    (1)终止条件:移动最小号
    (2)非最左到最右:三个步骤
    (3)最左到最右:五个步骤
public static void main(String[] args) {
int num = 4;

// solution 1
int steps1 = hanoiProblem1(num, "left", "mid", "right");
System.out.println("It will move " + steps1 + " steps.");
}


public static int hanoiProblem1(int num, String left, String mid,
String right) {
if (num < 1) {
return 0;
}
return process(num, left, mid, right, left, right);
}

public static int process(int num, String left, String mid, String right,String from, String to) {
if (num == 1) {
if (from.equals(mid) || to.equals(mid)) {
System.out.println("Move 1 from " + from + " to " + to);
return 1;
} else {
System.out.println("Move 1 from " + from + " to " + mid);
System.out.println("Move 1 from " + mid + " to " + to);
return 2;
}
}
if (from.equals(mid) || to.equals(mid)) {
String another = (from.equals(left) || to.equals(left)) ? right : left;
int part1 = process(num - 1, left, mid, right, from, another);
int part2 = 1;
System.out.println("Move " + num + " from " + from + " to " + to);
int part3 = process(num - 1, left, mid, right, another, to);
return part1 + part2 + part3;
} else {
int part1 = process(num - 1, left, mid, right, from, to);
int part2 = 1;
System.out.println("Move " + num + " from " + from + " to " + mid);
int part3 = process(num - 1, left, mid, right, to, from);
int part4 = 1;
System.out.println("Move " + num + " from " + mid + " to " + to);
int part5 = process(num - 1, left, mid, right, from, to);
return part1 + part2 + part3 + part4 + part5;
}
}

2.非递归,用栈来模拟塔