这题刚看的时候硬是没搞懂,knight,这英语。。。不想说什么。后来在网上搜索了一下题意才知道是按象棋里面马那样斜着走。
用广搜,把每一个位置的步数记录,八个方向搜索。
这题刚开始用数组存步数,然后由于总是Output Limit Exceeded,实在找不出原因,改用num记数,还一样,再改用结构体中的stp,
也还是Output Limit Exceeded,其实这根本就不是这个问题!
最后实在想不出什么错误了,把scanf改成cin马上就过来,这坑爹的系统,哪位大神能帮忙解释一下原因。。。。
#include<iostream>
#include<queue>
using namespace std;
int v[12][12];//标记是否走过
char st ,en;
int sta,end;
int r1,r2,num;
int d[8][2]={{1,2}, {2,1}, {1,-2} ,{2,-1} ,{-1,2} ,{-2,1} ,{-2,-1} ,{-1,-2}};//八个方向
struct node{
int xx,yy,stp;
}n,m;//存坐标和步数
void bfs(int x,int y)//广搜
{
int i;
queue<node>q;//广搜都是用队列来实现,队列相当于一个数组
n.stp=0;
n.xx=x;
n.yy=y;
q.push(n);
while(!q.empty())
{
n=q.front();
q.pop();
if(n.xx==r2 && n.yy==end)
return;
for(i=0;i<8;i++)
{
m.xx=n.xx+d[i][0];
m.yy=n.yy+d[i][1];
if(!v[m.xx][m.yy] && m.xx>=1 && m.yy>=1 && m.xx<=8 && m.yy<=8)
{
//num++;
m.stp=n.stp+1;
v[m.xx][m.yy]=1;
q.push(m);
}
}
}
}
int main()
{
// while(scanf("%c%d %c%d",&st,&sta,&en,&end))
while(cin>>st>>sta>>en>>end)
{
getchar();
memset(v,0,sizeof(v));
num=0;
r1=st-'a'+1;
r2=en-'a'+1;
// cout<<r1<<' '<<r2<<endl;
bfs(r1,sta);
//cout<<v[r2][end]<<endl;
printf("To get from %c%d to %c%d takes %d knight moves.\n",st,sta,en,end,n.stp);
}
return 0;
}