递归及汉诺塔问题

递归三要素

一定有一种可以退出程序的情况;
总是在尝试将一个问题化简到更小的规模
父问题与子问题不能有重叠的部分

汉诺塔问题描述

将A塔上的盘子移动到C塔上,期间大盘子不能放在小盘子上。

算法描述如下

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

namespace hanoi
{
    class Program
    {
        static void Main(string[] args)
        {
            hanoi(5, "A", "B", "C");
        }

        static void hanoi(int n, string origin, string tmp, string destination)
        {
            if (n == 1)
            {
                move(origin, destination); //第一个盘子从A移动到C
            }
            else {
                hanoi(n - 1, origin, destination,tmp); //将从上到下的第1到n-1个盘子,从A移动到B,用C做辅助
                move(origin, destination);  //将最后一个盘子从A移动到C
                hanoi(n - 1,tmp,destination,origin);    //将B上从1到n-1个盘子移动到C上,A做辅助

            }
        }

        static void move(string origin,string destination)
        {
            Console.WriteLine("Move the plate from "+origin+" to "+destination);
        }
    }
}

你可能感兴趣的:(递归及汉诺塔问题)