zoukankan      html  css  js  c++  java
  • 汉诺塔问题

    思路:

    当有多个盘子时,永远将盘子看作只有两个,位于最下面的一个盘子(A),跟其他的所有盘子(看做一个B),那么只需要先将B先放到中间位置,在将A放到目标位置,最后将A放到目标位置即可。当仅仅只有一个盘子时,直接将盘子从原始位置移动到目标位置。

    package DataStruct.Alg;
    
    public class Hanio {
        public static void Hanota(int n,char from,char in,char to)
        {
            //当仅有一个盘子时
           if (n==1)
           {
               System.out.println("第"+n+"个盘子"+"从"+from+"柱子移动到"+to+"柱子");
           }
           //当有多个盘子时,将其看作只有两个盘子,最下面一个,最上面一个
           else {
               //将最上面一个盘子移动到中间in位置
               Hanota(n-1,from,to,in);
               //将最下面的一个盘子移动到to位置
               System.out.println("第"+n+"个盘子"+"从"+from+"柱子移动到"+to+"柱子");
               //将最上面的一个盘子移动到to位置
               Hanota(n-1,in,from,to);
           }
        }
    
        public static void main(String[] args)
        {
            Hanota(3,'A','B','C');
        }
    }

     

  • 相关阅读:
    Attributes in C#
    asp.net C# 时间格式大全
    UVA 10518 How Many Calls?
    UVA 10303 How Many Trees?
    UVA 991 Safe Salutations
    UVA 10862 Connect the Cable Wires
    UVA 10417 Gift Exchanging
    UVA 10229 Modular Fibonacci
    UVA 10079 Pizza Cutting
    UVA 10334 Ray Through Glasses
  • 原文地址:https://www.cnblogs.com/dloading/p/10745925.html
Copyright © 2011-2022 走看看