【C#】汉诺塔移动步骤打印C#实现

由于群友在群里说起汉诺塔算法....于是我“偷偷摸摸”地了解一下这玩意,然后在VS console用C# 编写实现 打印汉诺塔每一步移动。

以下为使用递归方法完成的汉诺塔打印:

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

namespace 自制汉诺塔
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入hanoi的盘子数:");
            int numberInput = int.Parse(Console.ReadLine());
            Hanoi hanoi = new Hanoi(numberInput);
            Console.WriteLine("需要移动的次数:" + hanoi.moveTimes);
            Console.WriteLine("初始状态:");
            hanoi.Print();
            Console.WriteLine("开始移动:");
            hanoi.GoHanoi();
            Console.ReadKey();
        }
    }

    public class Hanoi
    {
        public List<int> frist = new List<int>();     
        public List<int> second = new List<int>();      
        public List<int> third = new List<int>();     
        public int number;                  //盘子数目
        public int moveTimes;               //移动次数

        //构造汉诺塔
        public Hanoi(int number)
        {
            this.number = number;
            moveTimes = (int)(Math.Pow(2, number) - 1);
            for(int i =number-1; i >= 0; i--)
            { 
                frist.Add(i+1);
            }
        }

        public void Print()
        {
            Console.WriteLine();
            for(int i = number - 1; i >= 0; i--)
            {
                string oneString = (frist.Count > i ? frist[i] : 0).ToString();
                string twoString = (second.Count > i ? second[i] : 0).ToString();
                string threeString = (third.Count >i ? third[i] : 0).ToString();
                Console.WriteLine(oneString + "\t" + twoString + "\t" + threeString);
                
            }
        }

        public void Step(int num, ref List<int> initial, ref List<int> target)
        {
            target.Add(initial[initial.Count - 1]);
            initial.Remove(initial[initial.Count - 1]);
            Print();
        }

        public void Exchange(int num, ref List<int> initial, ref List<int> target, ref List<int> replace)
        {
            if (num == 1)
            {
                Step(num, ref initial, ref replace);
            }
            else
            {
                Exchange(num - 1, ref initial, ref replace, ref target);
                Step(num, ref initial, ref replace);
                Exchange(num - 1, ref target, ref initial, ref replace);
            }
        }


        public void GoHanoi()
        {
            Exchange(number, ref frist, ref second, ref third);
        }
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值