#include<stdio.h>
#define N 8
int vis[N][N];
int step[N][N];
int dx[8] = {1,2,2,1,-1,-2,-2,-1};
int dy[8] = {2,1,-1,-2,-2,-1,1,2};
int bfs(int x, int y, int target)
{
int front = 0, rear = 0, u, d;
int q[70];
u = N * x + y;
if(u == target) return 0;
step[x][y] = 0;
q[rear++] = u;
while(front < rear)
{
u = q[front++];
x = u/N;
y = u%N;
for(d = 0; d < 8; d++)
{
int nx = x + dx[d], ny = y + dy[d];
if(nx >= 0 && nx < N && ny >= 0 && ny < N && vis[nx][ny] == 0)
{
if(nx * N + ny == target) return step[x][y] + 1;
q[rear++] = nx * N + ny;
vis[nx][ny] = 1;
step[nx][ny] = step[x][y] + 1;
}
}
}
}
void ReadInput()
{
char start[3], end[3];
while(scanf("%s%s", start, end) == 2)
{
int x = start[0] - 'a';
int y = start[1] - '1';
int ex = end[0] - 'a';
int ey = end[1] - '1';
memset(vis, 0, sizeof(vis));
memset(step, 0, sizeof(step));
printf("To get from %s to %s takes %d knight moves.\n",start,end,bfs(x,y,ex*N+ey));
}
}
UVa 439 Knight Moves
最新推荐文章于 2021-07-31 22:20:00 发布