UVA - 439 Knight Moves

来源:互联网 发布:电子cad软件 编辑:程序博客网 时间:2024/06/05 22:54

题目大意:求马走到目的要走几步

解题思路:用队列保存上一步,然后在一个个和目的的坐标对比,注意不要越界

#include<cstdio>#include<cstdlib>#include<cstring>#include<queue>using namespace std;struct step {int x;int y;int num;};int mx[8] = {-2,-2,-1,-1,1,2,2,1};int my[8] = {-1,1,-2,2,-2,-1,1,2};int min;int vis[12][12];int dx;int dy;void bfs(int x, int y) {queue<step> q;step t, p;memset(vis,0,sizeof(vis));vis[x][y] = 1;t.x = x;t.y = y;t.num = 0;q.push(t);while(!q.empty()) {t = q.front();q.pop();if(t.x == dx && t.y == dy) {printf("takes %d knight moves.\n", t.num);return ;}for(int i = 0; i < 8; i++) {p.x = t.x + mx[i];p.y = t.y + my[i];if(p.x > 0 && p.x <= 8 && p.y > 0 && p.y <= 8 && !vis[p.x][p.y]) {p.num = t.num + 1;vis[p.x][p.y] = 1;q.push(p);}}}}int main() {char y1, y2;int x1, x2;int x, y;while(scanf("%c%d %c%d", &y1, &x1, &y2, &x2) != EOF) {x = x1 ;y = y1 - 'a' + 1;dx = x2;dy = y2 - 'a' + 1;getchar();printf("To get from %c%d to %c%d ",y1,x1,y2,x2);bfs(x,y);}return 0;}


0 0
原创粉丝点击