C#递归实现:汉诺塔
汉诺塔背景:约19世纪末,在欧州的商店中出售一种智力玩具,在一块铜板上有三根杆,最左边的杆上自上而下、由小到大顺序串着由64个圆盘构成的塔。目的是将最左边杆上的盘全部移到右边的杆上,条件是一次只能移动一个盘,且不允许大盘放在小盘的上面。
递归实现汉诺塔的方法如下:
private static void Move(int count, char A, char B, char C)
{
if (count < 1)
{
throw new Exception("数量不能小于1!");
}
else if (count == 1)
{
Console.WriteLine("Move disc {0}----->{1}", A, C);
}
else
{
Move(count - 1, A, C, B);
Console.WriteLine("Move disc {0}----->{1}", A, C);
Move(count - 1, B, A, C);
}
}
public static void Main(string[] args)
{
int count = 2;
Console.WriteLine("Task: Move {0} discs from A pass B to C", count);
Move(count, 'A', 'B', 'C');
}
{
if (count < 1)
{
throw new Exception("数量不能小于1!");
}
else if (count == 1)
{
Console.WriteLine("Move disc {0}----->{1}", A, C);
}
else
{
Move(count - 1, A, C, B);
Console.WriteLine("Move disc {0}----->{1}", A, C);
Move(count - 1, B, A, C);
}
}
public static void Main(string[] args)
{
int count = 2;
Console.WriteLine("Task: Move {0} discs from A pass B to C", count);
Move(count, 'A', 'B', 'C');
}
本贴子以“现状”提供且没有任何担保,同时也没有授予任何权利
This posting is provided "AS IS" with no warranties, and confers no rights.
This posting is provided "AS IS" with no warranties, and confers no rights.
浙公网安备 33010602011771号