(C#)汉诺塔

/*
 当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();
        }
    }
}

 

    原文作者: 汉诺塔问题
    原文地址: https://blog.csdn.net/chenglin1986/article/details/6120357
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞