fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. #define io {ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);}
  4.  
  5. const int INF=1<<30;
  6. int stp[8][8];
  7. int dx[8]={-2,-2,-1,-1, 1, 1, 2, 2};
  8. int dy[8]={-1, 1,-2, 2,-2, 2,-1, 1};
  9.  
  10. struct NODE{
  11. int x, y;
  12. NODE(int x=0,int y=0):x(x),y(y){};
  13. bool InRange(){
  14. return 0<=x and x<8 and 0<=y and y<8; }
  15. } nxt, now;
  16.  
  17. int main(){
  18. io
  19. string s, e;
  20. // input
  21. while( cin>>s>>e ){
  22. NODE S=NODE(s[0]-'a',s[1]-'1');
  23. NODE E=NODE(e[0]-'a',e[1]-'1');
  24.  
  25. for(int x=0; x<8; x++)
  26. for(int y=0; y<8; y++)
  27. stp[x][y]=INF;
  28. deque<NODE> Q={S};
  29. stp[S.x][S.y]=0;
  30. while( !Q.empty() ){
  31. now=Q.front();
  32. Q.pop_front();
  33. for(int i=0; i<8; i++){
  34. nxt=NODE(now.x+dx[i],now.y+dy[i]);
  35. if( nxt.InRange() and stp[nxt.x][nxt.y]==INF ){
  36. stp[nxt.x][nxt.y]=stp[now.x][now.y]+1;
  37. Q.push_back(nxt);
  38. }
  39. }
  40. }
  41. // output
  42. cout<<"To get from "<<s<<" to "<<e<<" takes "<<stp[E.x][E.y]<<" knight moves.\n";
  43. }
  44. }
Success #stdin #stdout 0.01s 5516KB
stdin
e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6
stdout
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.