Knight Moves
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 30 Accepted Submission(s) : 19
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.
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<string>
#include<fstream>
using namespace std;
bool used[310][310];
struct squ{
char x;
char y;
int a;
int b;
long step;
};
long bfs(char x1,char y1,char x2,char y2){
queue<squ>que;
squ tp,ans,des;
squ tn;
int e;
int der[8][2] = {{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{-2,1},{2,-1},{-2,-1}};
int i;
ans.x=x1;ans.a=x1-'a'+1;
ans.y=y1;ans.b=y1-'0';
des.x=x2;des.a=x2-'a'+1;
des.y=y2;des.b=y2-'0';
ans.step=0;
used[ans.a][ans.b]=false;
que.push(ans);
//printf("dd");
while(1){
tp=que.front();
que.pop();
//printf("dd");
for(e=0;e<8;e++){
tn.a=tp.a+der[e][0];
tn.b=tp.b+der[e][1];
if(tn.a>=1&&tn.a<=8&&tn.b>=1&&tn.b<=8){
if(used[tn.a][tn.b]){
used[tn.a][tn.b]=false;
ans.a=tn.a;
ans.b=tn.b;
ans.step=tp.step+1;
que.push(ans);
if(ans.a==des.a&&ans.b==des.b)
return ans.step;
}
}
}
}
}
int main(){
char s1[3],s2[3];
int sum;
//ifstream cin("input.txt");
//freopen("input .txt","r",stdin);
while(scanf("%s %s",s1,s2)!=EOF){
//while(gets(s1)!=NULL){
memset(used,true,sizeof(used));
if(!strcmp(s1,s2))
cout<<"To get from "<<s1<<" to "<<s2<<" takes 0 knight moves."<<endl;
else{
sum=bfs(s1[0],s1[1],s2[0],s2[1]);
cout<<"To get from "<<s1<<" to "<<s2<<" takes "<<sum<<" knight moves."<<endl;
}
//printf("dd");
}
return 0;
}