[关闭]
@lychee123 2017-07-04T06:58:32.000000Z 字数 1558 阅读 1054

Knight Moves(裸奔BFS)

搜索


  1. #include<stdio.h>
  2. #include<queue>
  3. #include<string.h>
  4. #include<algorithm>
  5. using namespace std;
  6. int dir[8][2]={1,2,-1,2,1,-2,-1,-2,2,1,-2,-1,-2,1,2,-1};//方向数组
  7. int vis[10][10];//标记该点是否走过
  8. int i,j,x,y,ex,ey,num;//ex,ey表示终点坐标,num表示最少走的步数
  9. char a[3],b[3];
  10. struct node
  11. {
  12. int x,y,step;
  13. };
  14. int BFS()
  15. {
  16. node now,next;
  17. queue<node>q;
  18. now.x=x;
  19. now.y=y;
  20. now.step=0;
  21. if(now.x==ex&&now.y==ey)
  22. return now.step;
  23. q.push(now);
  24. memset(vis,0,sizeof(vis));
  25. vis[x][y]=1;//标记是否走过,同时记录从起点到该点走的最小步数(vis起点的值没有实际意义,只是用来标记)
  26. while(!q.empty())
  27. {
  28. now=q.front();//取出队首
  29. q.pop();//队首出队
  30. if(now.x==ex&&now.y==ey)
  31. {
  32. return vis[now.x][now.y];
  33. }
  34. for(i=0;i<8;i++)//八个方向
  35. {
  36. next.x=now.x+dir[i][0];
  37. next.y=now.y+dir[i][1];
  38. if(next.x>0&&next.x<=8&&next.y>0&&next.y<=8&&vis[next.x][next.y]==0)//边界和条件
  39. {
  40. next.step=now.step+1;
  41. vis[next.x][next.y]=next.step;
  42. q.push(next);
  43. }
  44. }
  45. }
  46. return -1;
  47. }
  48. int main()
  49. {
  50. while(~scanf("%s%s",a,b))
  51. {
  52. x=a[0]-'a'+1;
  53. y=a[1]-'0';
  54. ex=b[0]-'a'+1;
  55. ey=b[1]-'0';
  56. num=BFS();
  57. printf("To get from %s to %s takes %d knight moves.\n",a,b,num);
  58. }
  59. return 0;
  60. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注