汉诺塔

核心代码

        long hanoi_count = 0;//记录移动的次数
        public IActionResult HanNuoTa() { return View(); }
        [HttpPost]
        public IActionResult HanNuoTa(int num) {
            try
            {
                if (num<1)
                {
                    throw new Exception("请输入大于1的整数。");
                }
                StringBuilder sb = new StringBuilder();
                Stopwatch sw = new Stopwatch();
                sw.Start();
                Hanoi(num, 'A', 'B', 'C', sb);
                sw.Stop();
                sb.Append($"<div>耗时:{sw.ElapsedMilliseconds} 毫秒</div>");
                return Content(sb.ToString());
            }
            catch (Exception ex)
            {
                return Content("出错:" + ex.Message);
            }
        }
        /// <summary>
        /// 汉诺塔递归
        /// </summary>
        /// <param name="n">汉诺塔圆盘数量</param>
        /// <param name="a">a柱名称</param>
        /// <param name="b">b柱名称</param>
        /// <param name="c">c柱名称</param>
        /// <param name="sb">移动步骤字符串</param>
        void Hanoi(int n, char a, char b, char c, StringBuilder sb) {
            if (n==1)
            {
                sb.Append($"<div>第 {++hanoi_count} 次:{a} 柱 --> {c} 柱</div>");
            }
            else
            {
                Hanoi(n - 1, a, c, b,sb);
                sb.Append($"<div>第 {++hanoi_count} 次:{a} 柱 --> {c} 柱</div>");
                Hanoi(n - 1, b, a, c,sb);
            }
        }