BFS即可,字符串数组 size 定义成了 2 导致输入一直错误,应该是无法存入'\0' 引起的,待会儿再深究。
#includeusing namespace std;const int maxn = 8;typedef pair P;int d[maxn][maxn];char a[3],b[3];int x,y,x2,y2;void BFS(){ queue q; q.push(P(x,y)); d[x][y] = 0; while(!q.empty()){ P t = q.front(); q.pop(); x = t.first,y = t.second; for(int dx = -2;dx <= 2;dx++){ for(int dy = -2;dy <= 2;dy++){ if(!dx || !dy) continue; if(abs(abs(dy)-abs(dx)) == 0) continue; if(x+dx >= 0 && x+dx < maxn && y+dy >= 0 && y+dy < maxn && d[x+dx][y+dy] == -1){ q.push(P(x+dx,y+dy)); d[x+dx][y+dy] = d[x][y] + 1; if(x+dx == x2 && y+dy == y2) return; } } } }}int main(){ // freopen("data.in","r",stdin); // freopen("data.out","w",stdout); while(scanf("%s %s",a,b) == 2){ memset(d,-1,sizeof(d)); x = a[1] - '1'; y = a[0] - 'a'; x2 = b[1] - '1'; y2 = b[0] - 'a'; BFS(); printf("To get from %s to %s takes %d knight moves.\n",a,b,d[x2][y2]); } return 0;}