汉诺塔(Hanoi) C#解法

上帝创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上安大小顺序摞着64片黄金圆盘。
上帝命令婆罗门把圆盘从下面开始按大小顺序重新摆放在另一根柱子上。并且规定,在小圆盘上不能放大圆盘,在三根柱子之间一次只能移动一个圆盘。

有预言说,这件事完成时宇宙会在一瞬间闪电式毁灭。也有人相信婆罗门至今还在一刻不停地搬动着圆盘。 

 

用的是递归原理

 

代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HanoiProgram
{
    
class Program
    {
        
static long count = 0;
        
static void move(char x,char y)
        {
            Console.WriteLine("{0}--->{1}",x,y);
        }
        
static void hanoi(int n,char one,char two,char three)
        {
                
if (n == 1)
                {
                    count+=2;
                    move(one, two);
                    move(two, three);
                }
                
else
                {
                    count += 2;
                    hanoi(n - 1, one,two,three);
                    move(one, two);
                    hanoi(n - 1, three,two,one);
                    move(two,three);
                    hanoi(n - 1, one, two, three);
                }
        }
        
static void Main(string[] args)
        {
            Console.WriteLine("需要搬几个盘子");
            
int n =int.Parse(Console.ReadLine());
            hanoi(n, 'A''B''C');
            Console.WriteLine("搬迁结速;一共进行了{0}次的搬迁。", count);
            Console.Read();
        }

    }
}


 

posted @ 2009-12-15 09:15  gsrdell  阅读(1350)  评论(12编辑  收藏  举报