hdu 1372(simple BFS)

水深无声 2021-12-11 11:29 318阅读 0赞

Problem link adress:click here

This is a basic BFS problem.But the way of knight’s move is strange,if you don’t know the law of the knight’s move,you are likely to cann’t work the problem out.However,if you can find the regularity of the problem from the given cases’s data,you must be very smart!

  1. #include<iostream>
  2. #include<queue>
  3. #include<string>
  4. using namespace std;
  5. int map[10][10];
  6. char s1[5],s2[5];
  7. int visted[10][10];
  8. int x1,y1;
  9. int x2,y2;
  10. int dir[8][2]={1,2,-1,2,1,-2,-1,-2,2,1,2,-1,-2,1,-2,-1};
  11. struct node
  12. {
  13. int x,y,step;
  14. };
  15. void BFS()
  16. {
  17. int x,y;
  18. node cur,next;
  19. queue<node>q;
  20. memset(visted,0,sizeof(visted));
  21. cur.x=x1;
  22. cur.y=y1;
  23. cur.step=0;
  24. visted[x1][y1]=1;
  25. q.push(cur);
  26. while(!q.empty())
  27. {
  28. cur=q.front();
  29. q.pop();
  30. if(cur.x==x2&&cur.y==y2)
  31. {
  32. printf("To get from %s to %s takes %d knight moves.\n",s1,s2,cur.step);
  33. return ;
  34. }
  35. for(int i=0;i<8;i++)
  36. {
  37. next.x=x=cur.x+dir[i][0];
  38. next.y=y=cur.y+dir[i][1];
  39. next.step=cur.step+1;
  40. if(x>=0&&x<8&&y>=0&&y<8)
  41. {
  42. visted[x][y]=1;
  43. q.push(next);
  44. }
  45. }
  46. }
  47. }
  48. int main()
  49. {
  50. while(scanf("%s%s",s1,s2)!=EOF)
  51. {
  52. x1=s1[0]-'a';
  53. y1=s1[1]-'1';
  54. x2=s2[0]-'a';
  55. y2=s2[1]-'1';
  56. BFS();
  57. }
  58. return 0;
  59. }

  

转载于:https://www.cnblogs.com/heat-man/archive/2012/12/22/2829576.html

发表评论

表情:
评论列表 (有 0 条评论,318人围观)

还没有评论,来说两句吧...

相关阅读

    相关 HDU 1728(BFS)

    问题描述: 给定一个m × n (m行, n列)的迷宫,迷宫中有两个位置,gloria想从迷宫的一个位置走到另外一个位置,当然迷宫中有些地方是空地,gloria可以穿越,有些