龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > asp.net编程 >

C#递归实现汉诺塔(Hanoi) 游戏解法

时间:2009-12-21 11:47来源:未知 作者:admin 点击:
分享到:
汉诺塔简介 上帝创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上安大小顺序摞着64片黄金圆盘。 上帝命令婆罗门把圆盘从下面开始按大小顺序重新摆放在另一根柱子上。并

汉诺塔简介

上帝创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上安大小顺序摞着64片黄金圆盘。
上帝命令婆罗门把圆盘从下面开始按大小顺序重新摆放在另一根柱子上。并且规定,在小圆盘上不能放大圆盘,在三根柱子之间一次只能移动一个圆盘。
有预言说,这件事完成时宇宙会在一瞬间闪电式毁灭。也有人相信婆罗门至今还在一刻不停地搬动着圆盘。
下面使用递归实现

C# Code [http://www.xueit.com]
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();
        }
    }
}
精彩图集

赞助商链接