题目
汉诺塔问题的基础上,增加限制,必须得经过中间,不能直接从左到右或从右到左,求当塔有N层的时候打印最优移动过程和最优移动总步数。
要求
- 法一:递归法
- 法二:非递归法,用栈来模拟
解析
法一:主要分两种情况
- 情况一:从左到中,从中到左,从右到中,从中到右,在这种情况下,需要走三步,以从左到中为例,第一步,将1~N-1从左到右(递归实现),第二步,将第N块从左到中,第三步,将1~N-1从右到中
- 情况二:从左到右,从右到左,在这种情况下,需要走五步,以从左到右为例,第一步,将1~N-1从左到右(这里需要解释一下为什么不是从左到中,因为如果从左到中的话,第N块需要从左直接到右,这是不被允许的),第二步,将第N块从左到中,第三步,将1~N-1从右到左,第四步,将第N块从中到右,第五步,将1~N-1从左到右
法一源码
public int hanoiProblem1(int num,String left,String mid,String right){
if(num<1){
return 0
}
return ;
}
public 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)){
//3 steps eg:left->mid
String another=(from.equals(left)||to.equals(left))?rgiht:left;
//step 1:move n-1 from->another
int step1=process(num-1,left,mid,right,from,another);
//step2 :move n from->to only costs 1 step
int step2=1;
System.out.println("Move "+num+" from "+from+" to "+to);
//step 3:move n-1 another->to
int step3=process(num-1,left,mid,right,another,to);
return step1+step2+step3;
}else{
//5 steps eg:left->right
//step 1:move n-1 from->to
int step1=process(num-1,left,mid,right,from,to);
//step2 :move n from->mid only costs 1 step
int step2=1;
System.out.println("Move "+num+" from "+from+" to "+mid);
//step 3:move n-1 to->from
int step3=process(num-1,left,mid,right,to,from);
//step4 :move n mid->to only costs 1 step
int step4=1;
System.out.println("Move "+num+" from "+mid+" to "+to);
//step 5:move n-1 from->to
int step5=process(num-1,left,mid,right,from,to);
return step1+step2+step3+step4+step5;
}
}
法二非递归方法,见下一篇文章详解