📄 hannoi.cpp
字号:
// hannoi.cpp : Defines the entry point for the console application.
//
#include <stdio.h>
#include "stdafx.h"
#include <iostream.h>
#define width (rings+1)
void main()
{
int rings, last, next, x, z[500], s[3];
cout<<"how many rings? "<<endl;
cin>>rings;
for(x=1; x<=rings; x++) //将环放在第一个杆上
z[x]=width-x;
for(x=0; x<=2*width; x+=width) //给每一个杆设定基座
z[x]=1000;
// 如果有偶数个杆,将第一个环放在第二个杆上;如果是奇数个,则放在第三个杆上
if(rings%2==0)
{
last=1; s[2]=0; s[1]=1;
z[width+1]=z[rings];
}
else
{
last=2; s[1]=0; s[2]=1;
z[2*width+1]=z[rings];
}
cout<<"from 1 to "<<last+1<<endl;
s[0]=rings-1;
while(s[0]+s[1]) // 若第一个和第二个杆不是空的
{
//下一个将要移动的环比那些没有移动至最后的杆上的环要小
if(last==0) next=z[width+s[1]]<z[2*width+s[2]]?1:2;
if(last==1) next=z[s[0]]<z[2*width+s[2]]?0:2;
if(last==2) next=z[s[0]]<z[width+s[1]]?0:1;
//杆上最顶端的环必须是更为大的,且需要移动偶数个杆的距离
if((z[next*width+s[next]])>(z[last*width+s[last]])||((z[last*width+s[last]]-z[next*width+s[next]])%2==0))
last=3-next-last;
cout<<"from "<<next+1<<" to "<<last+1<<endl;
s[next]=s[next]-1; s[last]=s[last]+1; // 从杆next移动到杆last上
z[last*width+s[last]]=z[next*width+s[next]+1];
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -