由于群友在群里说起汉诺塔算法....于是我“偷偷摸摸”地了解一下这玩意,然后在VS console用C# 编写实现 打印汉诺塔每一步移动。
以下为使用递归方法完成的汉诺塔打印:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 自制汉诺塔
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入hanoi的盘子数:");
int numberInput = int.Parse(Console.ReadLine());
Hanoi hanoi = new Hanoi(numberInput);
Console.WriteLine("需要移动的次数:" + hanoi.moveTimes);
Console.WriteLine("初始状态:");
hanoi.Print();
Console.WriteLine("开始移动:");
hanoi.GoHanoi();
Console.ReadKey();
}
}
public class Hanoi
{
public List<int> frist = new List<int>();
public List<int> second = new List<int>();
public List<int> third = new List<int>();
public int number; //盘子数目
public int moveTimes; //移动次数
//构造汉诺塔
public Hanoi(int number)
{
this.number = number;
moveTimes = (int)(Math.Pow(2, number) - 1);
for(int i =number-1; i >= 0; i--)
{
frist.Add(i+1);
}
}
public void Print()
{
Console.WriteLine();
for(int i = number - 1; i >= 0; i--)
{
string oneString = (frist.Count > i ? frist[i] : 0).ToString();
string twoString = (second.Count > i ? second[i] : 0).ToString();
string threeString = (third.Count >i ? third[i] : 0).ToString();
Console.WriteLine(oneString + "\t" + twoString + "\t" + threeString);
}
}
public void Step(int num, ref List<int> initial, ref List<int> target)
{
target.Add(initial[initial.Count - 1]);
initial.Remove(initial[initial.Count - 1]);
Print();
}
public void Exchange(int num, ref List<int> initial, ref List<int> target, ref List<int> replace)
{
if (num == 1)
{
Step(num, ref initial, ref replace);
}
else
{
Exchange(num - 1, ref initial, ref replace, ref target);
Step(num, ref initial, ref replace);
Exchange(num - 1, ref target, ref initial, ref replace);
}
}
public void GoHanoi()
{
Exchange(number, ref frist, ref second, ref third);
}
}
}



279

被折叠的 条评论
为什么被折叠?



