Knight Moves
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 5341 Accepted Submission(s): 3262
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 <queue>
#include <cstring>
using namespace std;
struct node{
int x,y;
}s,e,head,next;
int vis[8][8];
int dir[8][2]={{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}};
int bfs(){
int cnt = 0;
queue<node> Q;
memset(vis,0,sizeof(vis));
Q.push(s);
vis[s.x][s.y]=1;
int Q_size;
while(!Q.empty()){
Q_size = Q.size();
cnt++;
while(Q_size--){
head = Q.front();
Q.pop();
if(head.x==e.x && head.y==e.y) return cnt-1;
for(int i=0; i<8; i++){
next.x = head.x+dir[i][0];
next.y = head.y+dir[i][1];
if(next.x>=0 && next.x<8 && next.y>=0 && next.y<8 && !vis[next.x][next.y]){
vis[next.x][next.y]=cnt;
Q.push(next);
}
}
}
}
}
int main()
{
char a[30],b[30];
while(cin>>a>>b){
s.x = a[1]-'0'-1;
s.y = a[0]-'a';
e.x = b[1]-'0'-1;
e.y = b[0]-'a';
cout<<"To get from "<<a<<" to "<<b<<" takes "<<bfs()<<" knight moves."<<endl;
}
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
struct node{
int x,y,cnt;
}Nnode[1000],head,next;
int x1,x2,y1,y2;
bool vis[8][8];
int dir[8][2]={{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}};
int bfs(){
memset(vis,false,sizeof(vis));
Nnode[0].x=x1;
Nnode[0].y=y1;
Nnode[0].cnt=0;
int start=0, end=1;
vis[x1][y1]=true;
while(start<end){
head = Nnode[start++];
if(head.x==x2 && head.y==y2) return head.cnt;
for(int i=0; i<8; i++){
int tx = head.x + dir[i][0];
int ty = head.y + dir[i][1];
if(tx<0 || tx>7 || ty<0 || ty>7 || vis[tx][ty]) continue;
vis[tx][ty]=true;
next.x = tx;
next.y = ty;
next.cnt = head.cnt+1;
Nnode[end++]=next;
}
}
}
int main()
{
char a[5],b[5];
while(cin>>a>>b){
x1 = a[1]-'0'-1;
y1 = a[0]-'a';
x2 = b[1]-'0'-1;
y2 = b[0]-'a';
cout<<"To get from "<<a<<" to "<<b<<" takes "<<bfs()<<" knight moves."<<endl;
}
}