HDU 1372 Knight Moves,bfs
http://acm.hdu.edu.cn/showproblem.php?pid=1372
简单广搜,秒过,关键在于国际象棋中马的走法是日,我日。。。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<stdio.h> #include<string.h> int visited[8][8],dir[8][2]={{-2,-1},{-2,1},{2,-1},{2,1},{-1,-2},{-1,2},{1,-2},{1,2}};//可以走四个方向 int sx,sy,ex,ey; struct node { int x,y,move; }s[100000]; int pd(int a,int b) { return (a<0||a>=8||b<0||b>=8); } int bfs() { int i,count=0,k,m,x,y; int q[100000],head,tail; memset(visited,0,sizeof(visited)); head=tail=0; s[count].x=sx; s[count].y=sy; s[count].move=0; q[head]=count; while(head<=tail) { k=q[head++]; if(s[k].x==ex&&s[k].y==ey) return s[k].move; m=s[k].move+1; for(i=0;i<8;i++) { x=s[k].x+dir[i][0]; y=s[k].y+dir[i][1]; if(pd(x,y))continue;//越界就进行下个循环 if(!visited[x][y]) { s[++count].x=x; s[count].y=y; s[count].move=m; q[++tail]=count; visited[x][y]=1; if(s[count].x==ex&&s[count].y==ey) return s[count].move; } } } } int main() { char b[4],e[4]; while(scanf("%s %s",b,e)!=EOF) { //printf("%s %s\n",b,e); sx=b[0]-'a'; sy=b[1]-'1'; ex=e[0]-'a'; ey=e[1]-'1'; printf("To get from %s to %s takes %d knight moves.\n",b,e,bfs()); } return 0; }