1. 思路
假设总共需要移动n
个盘子:
- 将
A柱
上的n-1
个盘子借助C柱
移向B柱
- 将
A柱
上仅剩的最后一个
盘子移向C柱
- 将
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;
}
}
}
}