zl程序教程

您现在的位置是:首页 >  其他

当前栏目

汉诺塔问题实现

2023-03-15 22:05:18 时间

其实就是三大步: 第一步:1-N-1个盘子从最左边的柱子放到中间 第二步:第N个盘子从最左边放到右边 第三步:1-N-1个盘子从中间放到左边 那肯定递归的入参里面必定有A,B,C和每一次要移动几个盘子

class Solution{
 public void hanota(List<Integer> A, List<Integer> B, List<Integer> C) {
process(A.size(),A,C,B);
}
   //from to other
    public void process(Integer N,List<Integer> from,List<Integer> to,List<Integer> other){
        if(N==1){//只移动一个盘子直接移动就好
             to.add(from.get(from.size()-1));
             from.remove(from.size()-1);
        }else{
        process(N-1,from,other,to);//N-1个从左边移到中间
        to.add(from.get(from.size()-1));
        from.remove(from.size()-1);
        process(N-1,other,to,from);//N-1个从中间移到右边
        }
    }
}