/// <summary> /// 移动 /// </summary> /// <param name="cnt">总数</param> /// <param name="src">源栈</param> /// <param name="temp">辅助栈</param> /// <param name="dst">终点栈</param> private void Move(int cnt, NamedStack src, NamedStack temp, NamedStack dst) { int val = 0; if (cnt <= 0) { return; } // 把n-1个圆盘以dst为辅助栈,从src移动到temp Move(cnt - 1, src, dst, temp); // 将第n个圆盘从src移动到dst,此时src应该只剩一个圆盘 val = src.Pop(); dst.Push(val); Console.WriteLine($"{val} {src.Name} -> {dst.Name}"); // 将剩余圆盘以src为辅助栈,从temp移动到dst Move(cnt - 1, temp, src, dst); }
public void Execute() { int cnt = 4; NamedStack a = new NamedStack { Name = "A" }; NamedStack b = new NamedStack { Name = "B" }; NamedStack c = new NamedStack { Name = "C" }; for (int i = cnt; i > 0; i--) { a.Push(i); } Move(cnt, a, b, c); }
/// <summary> /// Tower of Hanoi for 3 Peg /// </summary> /// <param name="sourcePeg">Source of Peg</param> /// <param name="targetPeg">Target of Peg</param> /// <param name="auxiliaryPeg">Auxiliary Peg</param> /// <param name="numberOfDiscs">Total number of discs</param> public static void TowerOfHanoi(NamedStack<int> sourcePeg, NamedStack<int> targetPeg, NamedStack<int> auxiliaryPeg, int numberOfDiscs) { // If only 1 disc then return and no need to performa any futher steps. Remove disc from source and place it to target if (numberOfDiscs == 1) { int disc = sourcePeg.Pop(); targetPeg.Push(disc); Console.WriteLine("Move 1 disk from {0} to {1}", sourcePeg.Name, targetPeg.Name); Console.WriteLine(string.Format("{0}={1} : {2}={3} : {4}={5}", sourcePeg.Name, sourcePeg.ArrayString, targetPeg.Name, targetPeg.ArrayString, auxiliaryPeg.Name, auxiliaryPeg.ArrayString)); return; } // Move N-1 disc from SourcePeg to AuxilaryPeg(Target now) using targetPeg(Auxilary now) TowerOfHanoi(sourcePeg, auxiliaryPeg, targetPeg, numberOfDiscs - 1); int temp = sourcePeg.Pop(); targetPeg.Push(temp); Console.WriteLine("Move {0} disk from {1} to {2}", temp, sourcePeg.Name, targetPeg.Name); Console.WriteLine(string.Format("{0}={1} : {2}={3} : {4}={5}", sourcePeg.Name, sourcePeg.ArrayString, targetPeg.Name, targetPeg.ArrayString, auxiliaryPeg.Name, auxiliaryPeg.ArrayString)); // Move N-1 disc from AuxilaryPeg(source now) to targetPeg(Target now) using SourcePeg(Auxilary now) TowerOfHanoi(auxiliaryPeg, targetPeg, sourcePeg, numberOfDiscs - 1); }