问题
汉诺塔问题比较经典,这里修改一下游戏规则:现在限制不能从最左侧的塔直接移动到最右侧,也不能从最右侧直接移动到最左侧,而是必须经过中间。求当塔有N层的时候,打印最优移动过程和最优移动总步数。
代码
代码1:经典递归算法
package com.iqiyi;
public class Code1_6_1 {
public static void main(String[] args){
int count=hanoi(5, "left", "right");
System.out.println(String.format("It will move %d steps.", count));
}
public static void move(int index,String from,String to){
System.out.println(String.format("Move %d from %s to %s", index, from, to));
}
public static int hanoi(int n,String from,String to){
if(n==1){
move(1, from, "mid");
move(1,"mid",to);
return 2;
}
int count1=hanoi(n-1, from, to);
move(n, from, "mid");
int count2=hanoi(n-1, to, from);
move(n, "mide", to);
int count3=hanoi(n-1, from, to);
return count1+count2+count3+2;
}
}
代码2:利用栈的非递归算法
package com.iqiyi;
import java.util.Stack;
public class Code1_6_2 {
public static int hanoi(int n){
Stack<Integer> stack1=new Stack<Integer>();
Stack<Integer> stack2=new Stack<Integer>();
Stack<Integer> stack3=new Stack<Integer>();
stack1.push(Integer.MAX_VALUE);
stack2.push(Integer.MAX_VALUE);
stack3.push(Integer.MAX_VALUE);
int t=n;
while(t>0){
stack1.push(t);
t--;
}
int count=0;
int action=1;
int first=stack1.pop();
stack2.push(first);
move(first, action);
count++;
while(stack3.size()!=(n+1)){
if(action==1 || action==2){
if(stack2.peek()>stack3.peek()){
first=stack3.pop();
stack2.push(first);
action=3;
}
else{
first=stack2.pop();
stack3.push(first);
action=4;
}
}
else {
if(stack1.peek()>stack2.peek()){
first=stack2.pop();
stack1.push(first);
action=2;
}
else{
first=stack1.pop();
stack2.push(first);
action=1;
}
}
move(first, action);
count++;
}
return count;
}
public static void move(int index,int action){
switch (action) {
case 1:
System.out.println(String.format("Move %d from 1 to 2", index));
break;
case 2:
System.out.println(String.format("Move %d from 2 to 1", index));
break;
case 3:
System.out.println(String.format("Move %d from 3 to 2", index));
break;
case 4:
System.out.println(String.format("Move %d from 2 to 3", index));
break;
default:
break;
}
}
public static void main(String[] args){
int count=hanoi(5);
System.out.println(String.format("It will move %d steps.", count));
}
}