POJ 2243解题报告
BFS
#include <stdio.h> #include <memory.h> #include <stdlib.h> const int maxn=15; int visit[maxn*maxn]; int dir[8][2]={{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2}}; char a[3]; char b[3]; int bfs(int st,int fin); int main() { while(scanf("%s",a)!=EOF) { scanf("%s",b); int sy=a[0]-'a'; int sx=a[1]-'1'; int fy=b[0]-'a'; int fx=b[1]-'1'; memset(visit,0,sizeof(visit)); int sl=sx*8+sy; int fl=fx*8+fy; if(sl==fl) { printf("To get from %s to %s takes 0 knight moves.\n",a,b); } else { printf("To get from %s to %s takes %d knight moves.\n",a,b,bfs(sl,fl)); } } return 0; } int bfs(int st,int fin) { int que[maxn*maxn]; int font=0; int rear=0; int distance[maxn*maxn]; distance[st]=0; que[rear++]=st; while(font<rear) { int on=que[font++]; int x=on/8; int y=on%8; int i; for(i=0;i<8;i++) { int dx=x+dir[i][0]; int dy=y+dir[i][1]; int on2=dx*8+dy; if(dx>=0&&dx<8&&dy>=0&&dy<8&&!visit[on2]) { visit[on2]=1; distance[on2]=distance[on]+1; que[rear++]=on2; if(on2==fin) return distance[on2]; } } } }