您的位置:首页 > 编程语言

学习笔记---递归的代码,解决经典的汉诺塔问题

2010-09-28 23:50 751 查看
一段递归的代码,汉诺塔问题

代码

using System;

namespace MoveHanoiTowerNS
{
class Program
{
static void Main(string[] args)
{
Console.Clear();
string input = null;
int num = -1;
while (true)
{
Console.Write("请输入参与挪动的盘子数量(1-20):");
input = Console.ReadLine();
num = Int32.Parse(input);
MoveTowerFunction.MoveDisk(num);
Console.WriteLine("\n---------------------------------------------------------------\n");
}
}
}

public static class MoveTowerFunction
{
private static readonly ConsoleColor oldbgcolor = Console.BackgroundColor;
private static readonly ConsoleColor oldfgcolor = Console.ForegroundColor;

private static int initnum = -1;
private static int midnum = -1;
private static int count = 0;

//公有方法作为对外联系的渠道
public static void MoveDisk(int num)
{
if (num >= 1 && num <= 20)
{
string start = "A";//表示起始柱
string help = "B";//表示中间的辅助柱
string target = "C";//表示移动的目标柱
initnum = (int)Math.Pow(2,num)-1;
midnum = initnum / 2;
Console.WriteLine(initnum.ToString());
moveDisk(num, start, help, target);
count = 0;
}
else
{
Console.WriteLine("可移动的盘子数量只能在1-20之间!");
}
}

//私有方法完成实际的内部计算
//递归法--方法内部继续逐次调用本方法,调用过程必须呈现为收敛性
private static void moveDisk(int n,string start,string help,string target)
{
if (n <= 1)//1个盘子
{
initnum--;
count++;
if (initnum > midnum)
{
Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.Yellow;
}
else if (initnum < midnum)
{
Console.BackgroundColor = ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.Blue;
}
else
{
Console.BackgroundColor = ConsoleColor.Yellow;
Console.ForegroundColor = ConsoleColor.Red;
}

Console.WriteLine(count+".\t" + start + "=================>" + target);
Console.BackgroundColor = oldbgcolor;
Console.ForegroundColor = oldfgcolor;
//returnColor();
}
else//2个以上(含2个)盘子
{
moveDisk(n - 1, start, target, help);//移动上面的n-1个盘子,从左柱到中柱
moveDisk(1, start, help, target);//移动最下面的1个盘子,从左柱到右柱
moveDisk(n - 1, help, start, target);//移动上面的n-1个盘子,从中柱到右柱
}
}

private static void returnColor()
{
Console.BackgroundColor = oldbgcolor;
Console.ForegroundColor = oldfgcolor;
}
}
}

/*
* 思考题:
* 参考共享下的彩色版哈诺塔程序,使用纯递归的手法来完成其编号及变色。 * 已解决,见代码
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: