POJ1915 Knight Moves

╰半夏微凉° 2022-06-12 12:08 208阅读 0赞
  1. #include <iostream> //结果正确,提交AC
  2. #include <cstdio> //统计最小步数(故用BFS,直接对应最短路)
  3. #include <queue>
  4. #include <cstring>
  5. using namespace std;
  6. const int MAXN = 100000 + 10;
  7. int n, sx, sy, ex, ey;
  8. int vis[310][310];
  9. int dir[8][2] = {1, -2, 2, -1, 2, 1, 1, 2,-1, -2, -2, -1, -2, 1, -1, 2}; //结果与 此遍历顺序无关
  10. struct node{
  11. int x;
  12. int y;
  13. int step;
  14. };
  15. int judge(int x, int y)
  16. {
  17. if(vis[x][y]==1 ||x < 0 || x >= n || y < 0 || y >= n)
  18. return 1 ;
  19. return 0;
  20. }
  21. void bfs()
  22. {
  23. queue<node>Q;
  24. node now, next;
  25. now.x = sx;
  26. now.y = sy;
  27. now.step = 0;
  28. Q.push(now);
  29. vis[sx][sy] = 1;
  30. while(!Q.empty()){
  31. now = Q.front();
  32. Q.pop();
  33. if(now.x == ex && now.y == ey){
  34. cout << now.step << endl;
  35. return;
  36. }
  37. for(int i = 0 ; i < 8 ; i++){
  38. next.x = now.x + dir[i][0];
  39. next.y = now.y + dir[i][1];
  40. if( judge(next.x, next.y) )
  41. continue;
  42. next.step = now.step + 1;
  43. Q.push(next);
  44. vis[next.x][next.y] = 1;
  45. }
  46. }
  47. }
  48. int main()
  49. {
  50. int T ;
  51. cin >> T;
  52. while(T--){
  53. memset(vis,0,sizeof(vis));//每用一次都要置零
  54. scanf("%d%d%d%d%d",&n,&sx,&sy,&ex,&ey);
  55. bfs();
  56. }
  57. return 0;
  58. }
  59. //input的第一行是样例的个数,
  60. //第二行是棋盘的大小,第三行是起点第四行是终点

发表评论

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

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

相关阅读