漢諾塔問題比較經典,這裏修改一下游戲規則:如今限制不能從最左側的塔直接移動到最右側,也不能從最右側直接移動到最左側,而是必須通過中間。求當塔有N層的時候,打印最優移動過程和最優移動總步數。java
代碼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:利用棧的非遞歸算法ide
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));
}
}
複製代碼