C#之汉诺塔的移动步骤显示算法

 

汉诺塔实现代码

 public partial class Form1 : Form
    {
        Ellipse[] elFrom;
        Ellipse[] elBy;
        Ellipse[] elTo;
        public Form1()
        {
            InitializeComponent();
        }
        void initialize(int count)//初始化
        {
            elFrom = new Ellipse[count];//对数组ellipse[]的初始化
            elBy = new Ellipse[count];
            elTo = new Ellipse[count];
            for (int i = 0; i < count; i++)//画环
            {
                elFrom[i] = new Ellipse() { width = 50 + 50 * i / count, height = (50 + 50 * i / count) / 4 };//width 和 height都是线型变量,height随着width的变化而变化
            }
        }
        void drawOne(Ellipse[] el,int startx,int starty,int height)
        {//画出一个图形(柱子和环!)
            Graphics g = this.CreateGraphics();
            Pen p1 = new Pen(Color.LightGray, 5);//使用宽度为5的画笔
            g.DrawLine(p1, startx, starty, startx, starty + height);//使用p1画汉诺塔的柱子
            Pen p2 = new Pen(Color.Gold, 3);
            for (int i = 0; i < el.Length; i++)
            {
                if (el[i] != null)//进行判段是因为,如果el[]中没有数据,就不画环只画柱子!
                {
                    g.DrawEllipse(p2, startx – el[i].width / 2, starty + 10 + 200 * i / el.Length, el[i].width, el[i].height);
                }//画环,根据需要画环的个数来确定环的坐标
            }
        }
        void drawGame()
        {//将全部的画出来
            Graphics g = this.CreateGraphics();
            g.Clear(Color.Brown);//清屏,即用该背景,每执行一次程序,清一次屏幕
            drawOne(elFrom, 100, 50, 200);
            drawOne(elBy, 300, 50, 200);
            drawOne(elTo, 500, 50, 200);
        }
        private class Ellipse//定义两个私有的属性width。和height
        {
            public int width { get; set; }
            public int height { get; set; }
        }

        private void button1_Click(object sender, EventArgs e)
        {、//创建Button1的单击事件
            initialize(4);
            drawGame();
        }
//算法部分:
        void hanoi(int count, Ellipse[] ellfrom, Ellipse[] ellby, Ellipse[] ellto)
        {
            if (count == 1)
            {
                move(1, ellfrom, ellto);
                return;
            }
            hanoi(count – 1, ellfrom, ellto, ellby);
            move(count, ellfrom, ellto);
            hanoi(count – 1, ellby, ellfrom, ellto);
        }
        void move(int num, Ellipse[] ellfrom, Ellipse[] ellto)
        {//写move方法
            ellto[num-1] = ellfrom[num-1];
            ellfrom[num-1] = null;
            System.Threading.Thread.Sleep(2000);//间隔2秒进行下一次运行
            drawGame();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            hanoi(4, elFrom, elBy, elTo);//在单机button2时调用hanoi方法!
        }
    }

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