汉诺塔(Hanoi) C#解法

原创|其它|编辑:郝浩|2009-12-15 09:45:57.000|阅读 438 次

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

# 界面/图表报表/文档/IDE等千款热门软控件火热销售中 >>

上帝创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上安大小顺序摞着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();
        }

    }
}

 


标签:

本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@evget.com

文章转载自:博客园

为你推荐

  • 推荐视频
  • 推荐活动
  • 推荐产品
  • 推荐文章
  • 慧都慧问
扫码咨询


添加微信 立即咨询

电话咨询

客服热线
023-68661681

TOP