fork(2) download
  1. #include <iostream>
  2. #include <math.h>
  3. using namespace std;
  4.  
  5. struct coord
  6. {
  7. int x,y;
  8. };
  9. const int n=8;
  10. int main()
  11. {
  12. int chessboard[n][n];
  13. bool k;
  14. string s0,s1;
  15. int step=0;
  16. coord start, finish;
  17. cin>>s0>>s1;
  18. start.x=(int)s0[0]-97;
  19. start.y=s0[1]-49;
  20. finish.x=(int)s1[0]-97;
  21. finish.y=s1[1]-49;
  22. for(int i=0;i<n;i++)
  23. for(int j=0;j<n;j++)
  24. chessboard[i][j]=-1;
  25. chessboard[start.x][start.y]=0;
  26. k=true;
  27. while(chessboard[finish.x][finish.y]==-1)
  28. {
  29. k=false;
  30. for(int i=0;i<n;i++)
  31. for(int j=0;j<n;j++)
  32. if(chessboard[i][j]==step)
  33. {
  34. for(int a=fmax(0,i-2);a<=fmin(n-1,i+2);a++)
  35. for(int b=fmax(0,j-2);b<=fmin(n-1,j+2);b++)
  36. if((chessboard[a][b]==-1)&&(((abs(i-a)==2)&&(abs(j-b)==1))||((abs(i-a)==1)&&(abs(j-b)==2))))
  37. {
  38. chessboard[a][b]=step+1;
  39. k=true;
  40. }
  41. }
  42. if(!k) chessboard[finish.x][finish.y]=0;
  43. else step++;
  44. }
  45. if (chessboard[finish.x][finish.y]==0) cout<<"start=finish"<<endl;
  46. else
  47. {
  48. coord path[8];
  49. path[0].x=finish.x;
  50. path[0].y=finish.y;
  51. for(int i=0;i<step;i++)
  52. {
  53. int x=path[i].x;
  54. int y=path[i].y;
  55. for(int a=fmax(0,x-2);a<=fmin(n-1,x+2);a++)
  56. for(int b=fmax(0,y-2);b<=fmin(n-1,y+2);b++)
  57. if((chessboard[a][b]==chessboard[x][y]-1)&&(((abs(x-a)==2)&&(abs(y-b)==1))||((abs(x-a)==1)&&(abs(y-b)==2))))
  58. {
  59. path[i+1].x=a;
  60. path[i+1].y=b;
  61. }
  62. }
  63. for(int i=step;i>=0;i--)
  64. cout<<(char)(path[i].x+97)<<path[i].y+1<<endl;
  65. }
  66. return 0;
  67. }
Success #stdin #stdout 0s 3280KB
stdin
a1
h8
stdout
a1
c2
e3
g2
h4
g6
h8