Knight Moves
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 13742 Accepted Submission(s): 8060
Of course you know that it is vice versa. So you offer him to write a program that solves the “difficult” part.
Your job is to write a program that takes two squares a and b as input and then determines the number of knight moves on a shortest route from a to b.
e2 e4 a1 b2 b2 c3 a1 h8 a1 h7 h8 a1 b1 c3 f6 f6
To get from e2 to e4 takes 2 knight moves. To get from a1 to b2 takes 4 knight moves. To get from b2 to c3 takes 2 knight moves. To get from a1 to h8 takes 6 knight moves. To get from a1 to h7 takes 5 knight moves. To get from h8 to a1 takes 6 knight moves. To get from b1 to c3 takes 1 knight moves. To get from f6 to f6 takes 0 knight moves.
#include<bits/stdc++.h>
using namespace std;
char s1[5];
char s2[5];
bool vis[10][10];
int d[8][2]={-2,1, -2,-1, -1,2, -1,-2, 1,2, 1,-2, 2,1, 2,-1};
int stx,sty,edx,edy,ans;
struct node{
int x,y,step;
node(){};
node(int _x,int _y,int _step)
{
x=_x; y=_y; step=_step;
}
bool operator <(const node &b)const
{
return step>b.step;
}
};
void bfs(int x,int y)
{
vis[x][y]=1;
node e1,e2;
priority_queue<node> que;
que.push(node(x,y,0));
while(que.size())
{
e1=que.top();que.pop();
if(e1.x==edx && e1.y==edy)
{
ans=e1.step;
break;
}
for(int i=0;i<8;i++)
{
e2.x=e1.x+d[i][0];
e2.y=e1.y+d[i][1];
e2.step=e1.step+1;
if(!vis[e2.x][e2.y] && 0 < e2.x && e2.x < 9 && 0 < e2.y && e2.y < 9 )
que.push(e2);
}
}
}
int main()
{
while(~scanf("%s %s",s1,s2))
{
// printf("%s %s\n",s1,s2);
stx=s1[0]-'a'+1;
sty=s1[1]-'0';
edx=s2[0]-'a'+1;
edy=s2[1]-'0';
memset(vis,0,sizeof(vis));
ans=0;
bfs(stx,sty);
printf("To get from %s to %s takes %d knight moves.\n",s1,s2,ans);
}
return 0;
}
271



被折叠的 条评论
为什么被折叠?



