1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| #include<iostream> using namespace std; int que[1010][2], dis[10][10], ans; int start_x, start_y, end_x, end_y, cur_x, cur_y, nx, ny; int dx[] = {-2, -2, -1, -1, 1, 1, 2, 2}; int dy[] = {-1, 1, -2, 2, -2, 2, -1, 1}; bool vis[10][10]; char Ax, Ay, Bx, By;
int BFS(){ que[0][0] = start_x; que[0][1] = start_y; vis[start_x][start_y] = true; for(int i=0, j=1 ; i<j ; i++){ cur_x = que[i][0]; cur_y = que[i][1]; if(cur_x == end_x && cur_y == end_y){ return dis[end_x][end_y]; } for(int k=0 ; k<8 ; k++){ nx = cur_x + dx[k]; ny = cur_y + dy[k]; if(nx <= 0 || nx > 8 || ny <= 0 || ny > 8) continue; if(!vis[nx][ny]){ vis[nx][ny] = true; dis[nx][ny] = dis[cur_x][cur_y]+1; que[j][0] = nx; que[j][1] = ny; j++; } } } return -1; }
int main(){ while(cin>>Ay>>Ax>>By>>Bx){ start_x = Ax-'0'; start_y = Ay-'a'+1; end_x = Bx-'0'; end_y = By-'a'+1; for(int i=0 ; i<10 ; i++){ for(int j=0 ; j<10 ; j++){ dis[i][j] = 0; vis[i][j] = false; } } ans = BFS(); cout<<"To get from "<<Ay<<Ax<<" to "<<By<<Bx<<" takes "<<ans<<" knight moves.\n"; }
return 0; }
|