poj 1915 Knight Moves【BFS】【简单】

待我称王封你为后i 2022-08-10 09:29 137阅读 0赞



Knight Moves














Time Limit: 1000MS   Memory Limit: 30000K
Total Submissions: 23541   Accepted: 11059

Description

1915_1.jpg

题目大意:输入N,表示棋盘大小为N*N,在输入两个坐标,分别是起始点与目标点,问从起始点到目标点的最少步数【马的行走规则与国际象棋中的一样】,

Sample Input

  1. 3
  2. 8
  3. 0 0
  4. 7 0
  5. 100
  6. 0 0
  7. 30 50
  8. 10
  9. 1 1
  10. 1 1

Sample Output

  1. 5
  2. 28
  3. 0

已Accept代码【c++提交】

  1. #include <cstdio>
  2. #include <queue>
  3. #include <cstring>
  4. using namespace std;
  5. int dx[] = {1, 1, -1, -1, 2, 2, -2, -2};
  6. int dy[] = {2, -2, 2, -2, 1, -1, 1, -1};
  7. int n;
  8. int dis[301][301];
  9. int a, b, x, y;
  10. typedef struct node{
  11. int x, y;
  12. node() {}
  13. node(int x, int y) : x(x), y(y) {}
  14. }node;
  15. void BFS() {
  16. queue <node> Q;
  17. memset(dis, 0x3f3f3f3f, sizeof(dis));
  18. Q.push(node(a, b));
  19. dis[a][b] = 0;
  20. while(!Q.empty()) {
  21. node k = Q.front();
  22. Q.pop();
  23. int r = k.x;
  24. int c = k.y;
  25. int ok = 0;
  26. for(int i = 0; i < 8; i++) {
  27. int nx = r + dx[i];
  28. int ny = c + dy[i];
  29. if(nx < 0 || nx >=n || ny < 0 || ny >= n)
  30. continue;
  31. if(dis[nx][ny] > dis[r][c] + 1) {
  32. dis[nx][ny] = dis[r][c] + 1;
  33. Q.push(node(nx, ny));
  34. }
  35. }
  36. }
  37. printf("%d\n", dis[x][y]);
  38. }
  39. int main() {
  40. int t;
  41. scanf("%d", &t);
  42. while(t--) {
  43. scanf("%d", &n);
  44. scanf("%d%d%d%d", &a, &b, &x, &y);
  45. BFS();
  46. }
  47. return 0;
  48. }

发表评论

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

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

相关阅读

    相关 poj 2488 A Knight's Journey(DFS)

    题目大意:给出一个国际棋盘的大小,判断马能否不重复的走过所有格,并记录下其中按字典序排列的第一种路径。   马的遍历是一道经典回溯题,当然还是DFS...这题有2个要密切注