2010-12-09 10:30:25Chris C.S Huang

[C#]河內塔(Towers of Hanoi)


河內塔目的:

將 n 個盤子由A塔柱搬至C塔柱。

規則:

1. 一次只能移動一個盤子。

2 搬運過程中,大盤子不能置於小盤子上方。

 

全部移動次數 = 2^n - 1

程式碼如下:

//        遞迴 : 河內塔問題 (Towers of Hanoi)
//        hanoi()   把 n 個盤子,從 form 柱,經由 by 柱,搬往 to 柱
//        作者: Chris Huang
//        程式語言: VC# 2008 Expression Edition

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DataStructure
{
    class Recursion
    {
        static void Main(string[] args)
        {
            
              int n = 0;
              Console.Write("Please input number => ");
                try {
                      n = Convert.ToInt16(Console.ReadLine());        // 讀入數字
                     
                }
                catch (Exception ex) {   // Argument is optional, no "When" keyword
                      
                          Console.WriteLine(ex.Message);
                          Console.Read();
                }
                        
            if(n>15){
                 Console.WriteLine("The calucation time will be too long to wait.....");          
                Console.WriteLine("Press Enter key to Exit");
                Console.Read();

            }
            else if (n < 0)
            {
                Console.WriteLine("input error, number must > 0");  ///小於零之數不合法
                Console.WriteLine("Press Enter key to Exit");
                Console.Read();

            }
            else
                Hanoi(n, "A", "B", "C");
    
              Console.WriteLine("Press Enter key to Exit");
              Console.Read();
        }
         //  把 n 個盤子,從 form 柱,經由 by 柱,搬往 to 柱
         public static void Hanoi(int n , String from, String by, String to)
         { 
          if(n > 0)
          {
            Hanoi(n - 1, from, to, by);
            Console.WriteLine("move no. {0} disk from {1} to {2}", n, from, to);
            Hanoi(n - 1, by, from, to);
          }
         }
    }
}