Kevin's Blog
阿新 • • 發佈:2019-01-27
/* 當n=1時,將第一個圓盤由A柱移動到C柱,完成移動 當n>1時,移動方法如下: 1.將1至n-1個圓盤由A移動到B柱 2.將第n個圓盤由A柱移動到C柱 3.將1至n-1個圓盤由B柱移動到C柱 */ using System; using System.Collections.Generic; using System.Text; namespace Hanoi { class Hanoi { static int i = 0; //n代表本步中要處理的盤子數 //a,b,c分別表示n號盤子原來所在的柱子,經由柱子,目標柱子 public static int MoveDisk(int n, char a, char b, char c) { if (n == 1) { //將1號盤子從a柱移動到c柱 Console.WriteLine("Move plate {0} from {1} to {2}", n, a, c); } else { //用本方法將剩餘n-1個盤子從a柱經由c柱移動到b柱 i = MoveDisk(n - 1, a, c, b); //將n號盤子從a柱移動到c柱 Console.WriteLine("Move plate {0} from {1} to {2}", n, a, c); //用本方法剩餘n-1個盤子從b柱經由a柱移動到c柱 i = MoveDisk(n - 1, b, a, c); } return ++i; } public static void Main(string[] args) { Console.WriteLine("Please enter the total number of Hanoi plates, then press Enter."); int n = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Progress of movement for {0} Hanoi plates: ", n); Console.WriteLine("Step counts: " + MoveDisk(n, 'A', 'B', 'C')); Console.ReadLine(); } } }