嗯...
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1372
这是一道很典型的bfs,跟马走日字一个道理,然后用dir数组确定骑士可以走的几个方向,然后从起点到终点跑一遍最典型的bfs即可...注意HDU的坑爹输入和输出...
AC代码:
#include<cstdio>
#include<iostream>
#include<queue>
#include<cstring> using namespace std; int ex, ey, sx, sy, step, g[][]; struct node{
int x, y, step;
}; int dir[][] = {{, }, {, }, {-, }, {, -}, {-, }, {, -}, {-, -}, {-, -}};
//方向
inline void bfs(){
memset(g, , sizeof(g));
queue<node> q;
node now, next;
now.x = sx;
now.y = sy;
now.step = ;
g[now.x][now.y] = ;
q.push(now);
while(!q.empty()){
now = q.front();
q.pop();
if(now.x == ex && now.y == ey){
step = now.step;
return;//找到终点
}
for(int i = ; i < ; i++){
next.x = now.x + dir[i][];
next.y = now.y + dir[i][];
if(next.x >= && next.x <= && next.y >= && next.y <= && !g[next.x][next.y]){
next.step = now.step + ;
g[next.x][next.y] = ;
q.push(next);
}
}
}
} int main(){
char c1, c2;
int s, t;
while(~scanf("%c%d %c%d", &c1, &s, &c2, &t)){
getchar();
sx = c1 - 'a' + ;
sy = s;
ex = c2 - 'a' + ;
ey = t;//起终点
bfs();
printf("To get from %c%d to %c%d takes %d knight moves.\n", c1, s, c2, t, step);
}
return ;
}
AC代码