题目链接:汉诺塔问题VII.
题目:
分析:
题目要求我们确定当前状态是否是汉诺塔的正确移动状态
对于N组数据,排列顺序有2的N次方,列举是不行的
所以我们可以选择递归调用
每次我们都能确定最大的盘子一定在初始位置或者目标位置
以3个圆盘为例,abc三根柱子,八种状态
分两步循环进行
- 先判断3号圆盘是否在a,b其中一个内
- 若在a,则判断2号圆盘是否在a,b其中一个内;
若在b,则判断2号圆盘是否在b,c内;
以题目中的例子前两个为例:
3
2
1
3号圆盘在a盘,正确
2号圆盘在b盘,正确
1号圆盘在c盘,正确
3
1
2
3号圆盘在a盘,正确
2号圆盘在c盘,错误
发生错误,后续步骤不再执行
AC代码
package Two;
import java.util.*;
public class 汉诺塔VII {
public static ArrayList<Integer>[] arr=new ArrayList[3];
public static boolean dfs(int n,int from,int mid,int to){
if(n<=0)return true;
if(arr[from].size()>0&&arr[from].get(0)==n){
arr[from].remove(0);
return dfs(n-1,from,to,mid);
}
else if(arr[to].size()>0&&arr[to].get(0)==n){
arr[to].remove(0);
return dfs(n-1,to,from,mid);
}
else return false;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0){
int n=sc.nextInt();
for(int i=0;i<3;i++){
arr[i]=new ArrayList<Integer>();
int m=sc.nextInt();
for(int j=0;j<m;j++){
int x=sc.nextInt();
arr[i].add(x);
}
}
System.out.println(dfs(n,0,1,2));
}
}
}