当前位置:编程学习 > C#/ASP.NET >>

C#解法之汉诺塔(Hanoi)

上帝创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上安大小顺序摞着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 =补充:软件开发 , C# ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,