【C#】汉诺塔C#代码实现(递归)

1. 思路

假设总共需要移动n个盘子:

  1. A柱上的n-1个盘子借助C柱移向B柱
  2. A柱上仅剩的最后一个盘子移向C柱
  3. B柱上的n-1个盘子借助A柱移向C柱

2.代码

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

namespace ConsoleDesktop
{
    class Program
    {
        static void Main(string[] args)
        {
            HanoiTower hanoi = new HanoiTower();
            int sum = hanoi.hanoiTowerSum(3, 'a', 'b', 'c');
            Console.WriteLine("总移动次数:{0}", sum);
        }
    }

    class HanoiTower
    {
        private void hanoiMove(char x, char y)
        {
            Console.WriteLine("{0} -> {1}", x, y);
        }

        public int hanoiTowerSum(int cnt, char a, char b, char c)
        {
            if(cnt == 1)
            {
                hanoiMove(a, c);
                return 1;
            }
            else
            {
                int sum = 0;
                sum += hanoiTowerSum(cnt - 1, a, c, b);		//步骤1
                hanoiMove(a, c); sum += 1;					//步骤2
                sum += hanoiTowerSum(cnt - 1, b, a, c);		//步骤3

                return sum;
            }
        }
    }
}

3. 运行结果

【C#】汉诺塔C#代码实现(递归)_第1张图片

你可能感兴趣的:(C#,c#,开发语言)