zoukankan      html  css  js  c++  java
  • 学习笔记递归的代码,解决经典的汉诺塔问题

    一段递归的代码,汉诺塔问题

    代码
    using System;

    namespace MoveHanoiTowerNS
    {
    class Program
    {
    static void Main(string[] args)
    {
    Console.Clear();
    string input = null;
    int num = -1;
    while (true)
    {
    Console.Write(
    "请输入参与挪动的盘子数量(1-20):");
    input
    = Console.ReadLine();
    num
    = Int32.Parse(input);
    MoveTowerFunction.MoveDisk(num);
    Console.WriteLine(
    "\n---------------------------------------------------------------\n");
    }
    }
    }

    public static class MoveTowerFunction
    {
    private static readonly ConsoleColor oldbgcolor = Console.BackgroundColor;
    private static readonly ConsoleColor oldfgcolor = Console.ForegroundColor;

    private static int initnum = -1;
    private static int midnum = -1;
    private static int count = 0;

    //公有方法作为对外联系的渠道
    public static void MoveDisk(int num)
    {
    if (num >= 1 && num <= 20)
    {
    string start = "A";//表示起始柱
    string help = "B";//表示中间的辅助柱
    string target = "C";//表示移动的目标柱
    initnum = (int)Math.Pow(2,num)-1;
    midnum
    = initnum / 2;
    Console.WriteLine(initnum.ToString());
    moveDisk(num, start, help, target);
    count
    = 0;
    }
    else
    {
    Console.WriteLine(
    "可移动的盘子数量只能在1-20之间!");
    }
    }

    //私有方法完成实际的内部计算
    //递归法--方法内部继续逐次调用本方法,调用过程必须呈现为收敛性
    private static void moveDisk(int n,string start,string help,string target)
    {
    if (n <= 1)//1个盘子
    {
    initnum
    --;
    count
    ++;
    if (initnum > midnum)
    {
    Console.BackgroundColor
    = ConsoleColor.Blue;
    Console.ForegroundColor
    = ConsoleColor.Yellow;
    }
    else if (initnum < midnum)
    {
    Console.BackgroundColor
    = ConsoleColor.Red;
    Console.ForegroundColor
    = ConsoleColor.Blue;
    }
    else
    {
    Console.BackgroundColor
    = ConsoleColor.Yellow;
    Console.ForegroundColor
    = ConsoleColor.Red;
    }

    Console.WriteLine(count
    +".\t" + start + "=================>" + target);
    Console.BackgroundColor
    = oldbgcolor;
    Console.ForegroundColor
    = oldfgcolor;
    //returnColor();
    }
    else//2个以上(含2个)盘子
    {
    moveDisk(n
    - 1, start, target, help);//移动上面的n-1个盘子,从左柱到中柱
    moveDisk(1, start, help, target);//移动最下面的1个盘子,从左柱到右柱
    moveDisk(n - 1, help, start, target);//移动上面的n-1个盘子,从中柱到右柱
    }
    }

    private static void returnColor()
    {
    Console.BackgroundColor
    = oldbgcolor;
    Console.ForegroundColor
    = oldfgcolor;
    }
    }
    }

    /*
    * 思考题:
    * 参考共享下的彩色版哈诺塔程序,使用纯递归的手法来完成其编号及变色。
    * 已解决,见代码
    */
  • 相关阅读:
    A1049. 命题逻辑
    矩形面积交:输出0.00
    完美的代价
    枚举孪生素数对
    改变参数的两种方法
    二面准备:React、Typescript、其他基础补充
    【TypeScript】基础及问题汇总
    【React】做一个百万答题小项目
    【React】相关题目总结
    【React】半小时深刻理解《半小时深刻理解React》(老套娃了)
  • 原文地址:https://www.cnblogs.com/cs_net/p/1837967.html
Copyright © 2011-2022 走看看