/* 汉诺塔问题:(Tower of Hanoi)

   此问题可以用递归方法解决:

       (1)、用C柱做过渡,将A柱上面的(n-1)盘子移到B.

       (2)、将A柱的最后一个盘子直接移到C柱上.

       (3)、用A柱做过渡,将B柱上的(n-1)个盘子移C柱上.*/

 

using System;

namespace 汉诺塔

{

       public class Class1

       {

              public static int i = 0;

              public static void Move(string A, string B)

              {

                     if(i++ % 10 == 0)

                     {

                            Console.WriteLine();

                     }

                     Console.Write(" {0}==>{1}  ",A,B);//移动盘子

              }

              public static void Hanta(int n,string A,string B,string C)

              {

                     if(n == 1)

                     {

                            Move(A,C);              //只移动一个盘子的汉诺塔问题

                     }

                     else

                     {

                            Hanta(n-1,A,C,B);     //将上面n-1个盘子移到B

                            Move(A,C);            //最下面一个盘子移到C

                            Hanta(n-1,B,A,C);     //Bn-1个盘子移到C

                     }

              }

      

              public static void Main(string[] args)

              {

                     Console.WriteLine("请输入你要挪动的盘子个数,输入Q退出:");

                     string str=Console.ReadLine();

                     string A="A",B="B",C="C";         //三个盘子ABC

                     while(str!="Q"&&str!="q")

                     {

                            Console.WriteLine("挪动{0}个盘子的步骤:",Convert.ToInt32(str));

                            Hanta(Convert.ToInt32(str),A,B,C);

                            Console.WriteLine();

                            Console.WriteLine("请继续输入你要挪动的盘子个数,输入Q退出:");

                            str=Console.ReadLine();         

                     }                  

              }

       }

}

posted on 2008-11-13 00:36  〆o殺殸纨o〆  阅读(217)  评论(1编辑  收藏  举报