小朋友的益智玩具,就是把一些圈圈从a->移到c,小的在上面,大的在下面。问你怎么做。
下面是图解:
写成代码就是:
先上个好理解版本的代码
if(N==1) 为basecase
void all(int N)
{
//开始位置:左->右
LeftToRight(N);
}
//1.左->右 三步 1.左到中 2.左到右 3.中到右
void LeftToRight(int N)
{
if(N==1)
{
cout<<"move 1 to left"<<endl;
}
else//N>1
{
LeftToMid(N-1);
cout<<"move N from left to right"<<endl;
MidToRight(N-1);
}
}
//2 左->中 1.左-右 2.左->中 3.右->中
void LeftToMid(int N)
{
if(N==1)
{
cout<<"move 1 to left"<<endl;
}
else//N>1
{
LeftToRight(N-1);
cout<<"move N from left to mid"<<endl;
RighttoMid(N-1);
}
}
//3.右->中 1.右->左 2.右->中 3.左—>中
void RightToMid(int N)
{
if(N==1)
{
cout<<"move 1 to left"<<endl;
}
else//N>1
{
LeftToMid(N-1);
cout<<"move N from left to right"<<endl;
MidToRight(N-1);
}
}
//4.右->左 1.右->中 2.右->左 3.中—>左
void RightToLeft(int N)
{
if(N==1)
{
cout<<"move 1 to right"<<endl;
}
else//N>1
{
//1.左->中 左->右 中->右
RightToMid(N-1);
cout<<"move N from right to left"<<endl;
MidToLeft(N-1);
}
}
//5.中->右 1.中->左 2.中->右 3.左—>右
void MidToRight(int N)
{
if(N==1)
{
cout<<"move 1 to left"<<endl;
}
else//N>1
{
ToMidToLeft(N-1);
cout<<"move N from Mid to right"<<endl;
LeftToRight(N-1);
}
}
//6.中->左 1.中->右 2.中->左 3.右—>左
void MidToLeft(int N)
{
if(N==1)
{
cout<<"move 1 to right"<<endl;
}
else//N>1
{
MidToRight(N-1);
cout<<"move N from mid to left"<<endl;
RightToLeft(N-1);
}
}
上面是过程,来个优雅简洁版的。
void func(int rest, int down, string from, string help, string to) {
if (rest == 1)
{
cout << "move " << down << " from " << from << " to " << to << endl;
}
else
{
func(rest - 1, down - 1, from, to, help);
func(1, down, from, help, to);
func(rest - 1, down - 1, help, from, to);
}
}
void hanoi(int n)
{
if (n > 0)
{
func(n, n, "left", "mid", "right");
}
}
void hanoi_main()
{
cout<<"***hanoi_main******"<<endl;
int n = 3;
hanoi(n);
}