题目链接:汉诺塔 问题 IX.
题目:
分析:
与汉诺塔 问题 VIII.非常类似,甚至稍微改几行代码就OK
在递归调用的代码中
当步数>2的(n-1)次方时
说明还有步数没走完
当步数==2的(n-1)次方时
说明步数恰好走完
当步数<2的(n-1)次方时
说明当前剩余步数不足以支持移动最大盘
AC代码
package Two;
import java.util.*;
public class 汉诺塔IX {
public static ArrayList<Integer>[] arr=new ArrayList[3];
public static void dfs(int n,long m,int from,int mid,int to){
if(n<=0)return ;
if(m==(long)(Math.pow(2, n-1)+0.000001)){
System.out.println(n);
}else if(m>(long)(Math.pow(2, n-1)+0.000001)){
arr[to].add(n);
m-=(long)(Math.pow(2, n-1)+0.000001);
dfs(n-1,m,mid,from,to);
}else{
arr[from].add(n);
dfs(n-1,m,from,to,mid);
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
int n=sc.nextInt();
long m=sc.nextLong();
if(n==0&&m==0)break;
for(int i=0;i<3;i++){
arr[i]=new ArrayList<Integer>();
}
dfs(n,m,0,1,2);
}
}
}