汉若塔游戏非递归解法(c#实现)
// 汉若塔游戏非递归解法(c#)
using System;
using System.Collections.Generic;
using System.Text;
namespace hanruota
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入盘子数:");
int diskCount =int.Parse( Console.ReadLine());
HanRuoTa a = new HanRuoTa(diskCount);
a.Run();
Console.ReadLine();
}
}
class HanRuoTa
{
Stack<Step> StepList = new Stack<Step>();
Step S;
public struct Step
{
public int N; //盘子个数
public int x, y, z;//位置
}
public HanRuoTa(int n)
{
S = new Step();
S.N = n;
S.x = 1;
S.y = 2;
S.z = 3;
}
public void Run()
{
//初始化问题
Step S1 = S;
StepList.Push(S1);
while(true)
{
//栈为空,代表问题已解决
if (StepList.Count == 0)
{
break;
}
else
{
int t=0;
S = StepList.Pop();
if (S.N <= 1)
{
Move(S.x, S.z);
}
else//分解为子问题压入栈(倒序)
{
//第三步
S1 = new Step();
S1 = S;
S1.N--;
Swap(ref S1.x, ref S1.y);
StepList.Push(S1);
//第二步
S1 = new Step();
S1 = S;
S1.N = 1;
StepList.Push(S1);
//第一步
S1 = new Step();
S1 = S;
S1.N--;
Swap(ref S1.y, ref S1.z);
StepList.Push(S1);
}
}
}
}
void Swap(ref int a, ref int b)
{
int t= a;
a = b;
b = t;
}
void Move(int f, int t)
{
Console.WriteLine(f.ToString() + "->" + t.ToString());
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace hanruota
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入盘子数:");
int diskCount =int.Parse( Console.ReadLine());
HanRuoTa a = new HanRuoTa(diskCount);
a.Run();
Console.ReadLine();
}
}
class HanRuoTa
{
Stack<Step> StepList = new Stack<Step>();
Step S;
public struct Step
{
public int N; //盘子个数
public int x, y, z;//位置
}
public HanRuoTa(int n)
{
S = new Step();
S.N = n;
S.x = 1;
S.y = 2;
S.z = 3;
}
public void Run()
{
//初始化问题
Step S1 = S;
StepList.Push(S1);
while(true)
{
//栈为空,代表问题已解决
if (StepList.Count == 0)
{
break;
}
else
{
int t=0;
S = StepList.Pop();
if (S.N <= 1)
{
Move(S.x, S.z);
}
else//分解为子问题压入栈(倒序)
{
//第三步
S1 = new Step();
S1 = S;
S1.N--;
Swap(ref S1.x, ref S1.y);
StepList.Push(S1);
//第二步
S1 = new Step();
S1 = S;
S1.N = 1;
StepList.Push(S1);
//第一步
S1 = new Step();
S1 = S;
S1.N--;
Swap(ref S1.y, ref S1.z);
StepList.Push(S1);
}
}
}
}
void Swap(ref int a, ref int b)
{
int t= a;
a = b;
b = t;
}
void Move(int f, int t)
{
Console.WriteLine(f.ToString() + "->" + t.ToString());
}
}
}