/* 思路:
1、BFS遍历,不必遍历全部
注意点:
1、8*8的棋盘格,骑士的走法与象棋中的马走法相同
*/
#include <cstdio>
#include <cstring>
const int MAX = 8;
int visit[MAX][MAX];
int dist[MAX][MAX];
const int dir_x[] = {-1, -2, -2, -1, 1, 2, 2, 1};
const int dir_y[] = {-2, -1, 1, 2, 2, 1, -1, -2};
const int DIR = sizeof(dir_x) / sizeof(dir_x[0]);
int st_y,st_x,ed_y,ed_x;
int qu_x[MAX*MAX];
int qu_y[MAX*MAX];
void bfs()
{
int front=0, rear=0;
dist[st_x][st_y] = 0;
if(st_x == ed_x && st_y == ed_y) return; //found
visit[st_x][st_y] = 1;
qu_x[rear]=st_x; qu_y[rear++]=st_y;
while(front < rear) {
st_x = qu_x[front]; st_y = qu_y[front++];
if(st_x == ed_x && st_y == ed_y) return; //found
for(int i=0; i<DIR; i++) {
int t_x = st_x + dir_x[i];
int t_y = st_y + dir_y[i];
if(!visit[t_x][t_y] && t_x>=0 && t_x<MAX && t_y>=0 && t_y<MAX) {
dist[t_x][t_y] = dist[st_x][st_y] + 1;
if(t_x == ed_x && t_y == ed_y) return; //found
visit[t_x][t_y] = 1;
qu_x[rear]=t_x; qu_y[rear++]=t_y;
}
}
}
}
int main ()
{
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif
char st[4];
char ed[4];
while(scanf("%s%s", st, ed)==2) {
st_y = st[0] - 'a';
st_x = st[1] - '1';
ed_y = ed[0] - 'a';
ed_x = ed[1] - '1';
memset(visit, 0, sizeof(visit));
bfs();
printf("To get from %s to %s takes %d knight moves.\n", st, ed, dist[ed_x][ed_y]);
}
return 0;
}
UVa 439 - Knight Moves
最新推荐文章于 2021-08-01 10:07:45 发布