按照象棋中马走的方向,判断两点间最短距离或不可到达;
http://poj.org/problem?id=2243
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int maxn=1001+5;
int dx[]={-2,-2,-1,-1,1,1,2,2};
int dy[]={-1,1,2,-2,2,-2,1,-1};
int sr,sc,er,ec;
int n,m;
struct Node
{
int r,c,time;
Node() {time=0;}
Node(int r,int c,int k):r(r),c(c),time(k) {}
};
Node no;
int visit[100][100];
string a,b;
void BFS(Node sta)
{
visit[sta.r][sta.c]=1;
queue<Node> Q;
Q.push(Node(sta.r,sta.c,sta.time));
while(!Q.empty())
{
Node x=Q.front();
Q.pop();
for(int i=0; i<8; i++)
{
int nr=x.r+dx[i];
int nc=x.c+dy[i];
if(nr>=0 && nr<=7 && nc>=0 && nc<=7 && !visit[nr][nc])
{
int time=x.time+1;
if(nr==no.r&&nc==no.c){
cout<<"To get from "<<a<<" to "<<b<<" takes "<<time<<" knight moves."<<endl;
return ;
}
visit[nr][nc]=1;
Q.push(Node(nr,nc,time));
}
}
}
cout<<"To get from "<<a<<" to "<<b<<" takes "<<"-1"<<" knight moves."<<endl;
}
int main()
{
while(cin>>a>>b)
{
memset(visit,0,sizeof(visit));
int ax=a[0]-'a';
int ay=a[1]-'1';
int ax1=b[0]-'a';
int ay1=b[1]-'1';
if(a==b)
{
cout<<"To get from "<<a<<" to "<<b<<" takes "<<"0"<<" knight moves."<<endl;
}
else{
no=Node(ax1,ay1,0);
BFS(Node(ax,ay,0));
}
}
return 0;
}