Advertisement
farsid

Untitled

Jul 13th, 2012
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<iostream>
  3. #include<queue>
  4. #include<string.h>
  5.  
  6. using namespace std;
  7.  
  8. struct Node
  9. {
  10. int r,c,d;
  11. };
  12.  
  13. char from[4];
  14. char to[4];
  15.  
  16. char chess[12][12];
  17. char vst[12][12];
  18.  
  19. queue<Node>Q;
  20.  
  21. int dx[]={2,2,-2,-2,1,-1,1,-1};
  22. int dy[]={1,-1,1,-1,2,2,-2,-2};
  23.  
  24. int bfs(Node S,Node T)
  25. {
  26. int i;
  27. memset(vst,0,sizeof(vst));
  28. while(!Q.empty())Q.pop();
  29. /*for(i=0;i<12;i++)
  30. {
  31. printf("\n");
  32. for(int j=0;j<12;j++)printf("%d",vst[i][j]);
  33. }*/
  34. Q.push(S);
  35. vst[S.r][S.c]=1;
  36. Node u,v;
  37. while(!Q.empty())
  38. {
  39. u=Q.front();
  40. //printf("%d %d %d\n",u.r,u.c,u.d);
  41. Q.pop();
  42. for(i=0;i<8;i++)
  43. {
  44. v=u;
  45. v.r+=dx[i];
  46. v.c+=dy[i];
  47.  
  48. if(chess[v.r][v.c]!=1)continue;
  49.  
  50. if(!vst[v.r][v.c])
  51. {
  52. vst[v.r][v.c]=1;
  53. v.d=u.d+1;
  54. //printf("%d %d %d\n",v.r,v.c,v.d);
  55. if(v.r==T.r && v.c==T.c)return v.d;
  56.  
  57. Q.push(v);
  58. }
  59. }
  60. }
  61. return 0;
  62. }
  63.  
  64. int main()
  65. {
  66.  
  67. int i,j,x;
  68. for(i=2;i<=9;i++)memset(chess[i]+2,1,8);
  69. while(scanf("%s %s",from,to)==2)
  70. {
  71. //for(i=2;i<=9;i++)memset(chess[i]+2,1,8);
  72. /*for(i=0;i<12;i++)
  73. {
  74. printf("\n");
  75. for(j=0;j<12;j++)printf("%d",chess[i][j]);
  76. }*/
  77. Node S,T;
  78. S.r=from[1]-47;
  79. S.c=from[0]-95;
  80. S.d=0;
  81. T.r=to[1]-47;
  82. T.c=to[0]-95;
  83. //printf("%d %d %d %d\n",S.r,S.c,T.r,T.c);
  84. x=bfs(S,T);
  85. //printf("%d\n",x);
  86. printf("To get from %s to %s takes %d knight moves.\n",from,to,x);
  87. }
  88. return 0;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement