POJ2243 Knight Moves(BFS)

来源:互联网 发布:java进阶书籍推荐 知乎 编辑:程序博客网 时间:2024/05/29 18:51

题意:

输入两组坐标,输出骑士从一个到另一个最少要几步(骑士走日字)

要点:

标准的BFS题,寻找最短路径,用队列做


15170656Seasonal2243Accepted176K16MSC++1099B2016-02-17 17:36:15

#include<stdio.h>#include<string.h>#include<stdlib.h>#include<queue>using namespace std;bool visit[20][20];int dx[8] = { -2, -2, -1, -1, 1, 1, 2, 2 };int dy[8] = { -1, 1, -2, 2, -2, 2, -1, 1 };struct node{int x;int y;char c;int num;};node a, b;queue<node> que;int xx, yy;void bfs(){que.push(a);visit[a.x][a.y] = false;while (!que.empty())//直到所有的点都遍历过{node temp = que.front();if (temp.x == b.x&&temp.y == b.y){printf("To get from %c%d to %c%d takes %d knight moves.\n", a.c, a.y, b.c, b.y, temp.num);return;}que.pop();for (int i = 0; i < 8; i++){node next;xx = temp.x + dx[i];yy = temp.y + dy[i];if (!visit[xx][yy] || xx < 1 || xx > 8 || yy < 1 || yy > 8)//越界就跳过continue;next.x = xx;next.y = yy;next.num = temp.num + 1;visit[xx][yy] = false;que.push(next);}}}int main(){while (~scanf("%c%d %c%d", &a.c, &a.y, &b.c, &b.y)){getchar();//除去换行符while (!que.empty())//每次都要要清空队列que.pop();a.x = a.c - 'a' + 1;b.x = b.c - 'a' + 1;a.num = 0;memset(visit, true, sizeof(visit));bfs();}return 0;}


0 0