题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=380
题目大意:马走日子形,给出起点和终点,输出最小步数。
分析:bfs,水过。
ac代码
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
typedef struct Q
{
int x;
int y;
int step;
}Q;
queue<Q> s;
char start[5], finish[5];
int sx, sy, ex, ey;
int dx[8] = {-1, -2, -2, -1, 1, 2, 2, 1};
int dy[8] = {-2, -1, 1, 2, 2, 1, -1, -2};
char vis[10][10];
int main()
{
while(scanf("%s %s", start, finish) != EOF)
{
while(!s.empty())s.pop();
memset(vis, 1, sizeof(vis));
sx = 9 - (start[1] - '0');
sy = start[0] - 'a' + 1;
ex = 9 - (finish[1] - '0');
ey = finish[0] - 'a' + 1;
//printf("%d %d %d %d\n", sx, sy, ex, ey);
int num;
vis[sx][sy] = 0;
Q a;
a.x = sx;
a.y = sy;
a.step = 0;
s.push(a);
while(!s.empty())
{
Q b = s.front();
s.pop();
if(b.x == ex && b.y == ey)
{
num = b.step;
break;
}
vis[b.x][b.y] = 0;
for(int i = 0; i < 8; i++)
{
int xx = b.x + dx[i];
int yy = b.y + dy[i];
int sp = b.step + 1;
if(xx >= 1 && xx <= 8 && yy >= 1 && yy <= 8 && vis[xx][yy] == 1)
{
Q c;
c.x = xx;
c.y = yy;
c.step = sp;
s.push(c);
}
}
}
printf("To get from %s to %s takes %d knight moves.\n", start, finish, num);
}
return 0;
}