{
//非递归解法
int n = 5; //这里的n表示圆盘的个数,我写死在程序里了
HannoiNotUseRecursion.Pillar[] pillar = new HannoiNotUseRecursion.Pillar[3]; //三根柱子的信息用结构数组存储
for (int i=0; i < pillar.Length;i++)
{
pillar[i].sElement = new Stack<int>();
}
HannoiNotUseRecursion.Creat(pillar, n); //给结构数组设置初值
long max = HannoiNotUseRecursion.Pow(2, n) - 1;//动的次数应等于2^n - 1
HannoiNotUseRecursion.Hannoi(pillar, max);//移动汉诺塔的主要函数
Console.Read();
}
{
/// <summary>
/// 计算x^y
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public static long Pow(int x, int y)
{
long sum = 1;
for (int i = 0; i < y; i++)
{
sum *= x;
}
return sum;
}
/// <summary>
/// 给柱子结构数组设置初值
/// </summary>
/// <param name="pillar">柱子</param>
/// <param name="n">圆盘个数</param>
public static void Creat(Pillar[] pillar, int n)
{
pillar[0].Name = 'A';
//把所有的圆盘按从大到小的顺序放在柱子A上
for (int i = 0; i < n; i++)
{
pillar[0].sElement.Push(n - i);
}
//柱子B,C上开始没有没有圆盘
for (int i = 0; i < n; i++)
{
pillar[1].sElement.Push(0);
pillar[2].sElement.Push(0);
}
//若n为偶数,按顺时针方向依次摆放 A B C
if (n % 2 == 0)
{
pillar[1].Name = 'B';
pillar[2].Name = 'C';
}
else //若n为奇数,按顺时针方向依次摆放 A C B
{
pillar[1].Name = 'C';
pillar[2].Name = 'B';
}
}
public static void Hannoi(Pillar[] pillar, long max) //移动汉诺塔的主要函数
{
int k = 0; //累计移动的次数
int i = 0;
int ch;
while (k < max)
{
//按顺时针方向把圆盘1从现在的柱子移动到下一根柱子
ch = pillar[i % 3].Pop();
pillar[(i + 1) % 3].Push(ch);
Console.WriteLine(string.Format("{0}: Move disk {1} from {2} to {3}", ++k, ch, pillar[i % 3].Name, pillar[(i + 1) % 3].Name));
i++;
//把另外两根柱子上可以移动的圆盘移动到新的柱子上
if (k < max)
{ //把非空柱子上的圆盘移动到空柱子上,当两根柱子都为空时,移动较小的圆盘
if (pillar[(i + 1) % 3].Top() == 0 ||
pillar[(i - 1) % 3].Top() > 0 &&
pillar[(i + 1) % 3].Top() > pillar[(i - 1) % 3].Top())
{
ch = pillar[(i - 1) % 3].Pop();
pillar[(i + 1) % 3].Push(ch);
Console.WriteLine(string.Format("{0}: Move disk {1} from {2} to {3}", ++k, ch, pillar[(i - 1) % 3].Name, pillar[(i + 1) % 3].Name));
}
else
{
ch = pillar[(i + 1) % 3].Pop();
pillar[(i - 1) % 3].Push(ch);
Console.WriteLine(string.Format("{0}: Move disk {1} from {2} to {3}", ++k, ch, pillar[(i + 1) % 3].Name, pillar[(i - 1) % 3].Name));
}
}
}
}
/// <summary>
/// 用来表示每根柱子的信息
/// </summary>
public struct Pillar
{
//存储每根柱子套的上的圆盘情况
public Stack<int> sElement;
//柱子的名字,可以是A,B,C中的一个
public char Name;
/// <summary>
/// 出栈
/// 把盘子从柱子中挪走
/// </summary>
/// <returns></returns>
public int Pop()
{
return sElement.Pop();
}
/// <summary>
/// 入栈
/// 把盘子放入柱子中
/// </summary>
/// <param name="x"></param>
public void Push(int x)
{
sElement.Push(x);
}
/// <summary>
/// 取栈顶元素
/// </summary>
/// <returns></returns>
public int Top()
{
if (sElement.Count == 0)
{
return 0;
}
else
{
return sElement.Peek();
}
}
}
}