求助:
def moveDisk(n,t1,t2,t3):
if n == 1:
print(t1,"-->",t3)
if n > 1:
moveDisk(n-1,t1,t3,t2)
print(t1,"-->",t3)
moveDisk(n-1,t2,t1,t3)
请问如何把这个递归的程序用堆栈转化为非递归的程序呀,谢谢大佬
public class MyTest1 {
public static void main(String[] args) throws NoSuchFieldException {
Hanoi(3,"A","B","C");
}
public static void Hanoi(int num , String t1,String t2,String t3){
Stack<MovePolice> stack = new Stack<>();
stack.push(new MovePolice(num,t1,t2,t3));
while(!stack.isEmpty()){
MovePolice top = stack.pop();
if(top.num ==1 ){
System.out.println(top.t1 + " → "+top.t2 + " → "+top.t3);
continue;
}
//1. (n-1)从t1 经过t3 到t2
//2. 1 从t1 经过t2 到t3
//3. (n-1)从t2 经过t1 到t3
//入栈步骤应该反着来
//3
stack.push(new MovePolice(top.num-1,top.t2,top.t1,top.t3));
//2
stack.push(new MovePolice(1,top.t1,top.t2,top.t3));
//1
stack.push(new MovePolice(top.num-1,top.t1,top.t3,top.t2));
}
}
}
//移动的策略
class MovePolice{
int num;
String t1; // src源跳板
String t2; // 中间过度的跳板
String t3; // dest目的跳板
public MovePolice(int num, String t1, String t2, String t3) {
this.num = num;
this.t1 = t1;
this.t2 = t2;
this.t3 = t3;
}
}
执行结果
A → B → C
A → C → B
C → A → B
A → B → C
B → C → A
B → A → C
A → B → C